package com.authine.cloudpivot.ext.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.exceptions.ServiceException;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizSchemaModel;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.domain.bizservice.BizDatabaseConnectionPool;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.engine.service.bizservice.BizDatabaseConnectionPoolService;
import com.authine.cloudpivot.engine.service.datasource.DataSourceService;
import com.authine.cloudpivot.engine.service.datasource.MyColumnMapRowMapper;
import com.authine.cloudpivot.engine.service.impl.datasource.TemplateDynamicMultiDataSource;
import com.authine.cloudpivot.ext.doman.CourseUpdateInfo;
import com.authine.cloudpivot.ext.doman.courseInfoVo;
import com.authine.cloudpivot.ext.repository.CourseUpdateRepository;
import com.authine.cloudpivot.ext.service.AttachmentService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: brookpeng
 * @Date: 2022/2/24 13:29
 */
@Slf4j
@RestController
@RequestMapping("/api/pages")
public class PagesUseController extends BaseController {

    @PersistenceContext
    EntityManager entityManager;

    @Autowired
    private CourseUpdateRepository courseUpdateRepository;

    @Autowired
    private BizObjectFacade bizObjectFacade;

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private PocZcController pocZcController;

    @Autowired
    private BizDatabaseConnectionPoolService connectionPoolService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/kcsbPageAdd")
    public ResponseResult<Map<String, Object>> kcsbPageAdd() {
        Map<String, Object> data = new HashMap<>();
        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);
        //String employeeNo = user.getEmployeeNo();
        String name = user.getName();
        String username = user.getUsername();

        // 人员职位获取
        String zw = "";
        StringBuilder selectUserInfoSql = new StringBuilder();
        selectUserInfoSql.append("SELECT * FROM view_user_eac WHERE username = '" + username + "';");
//        List<Map<String, Object>> userInfo = entityManager.createNativeQuery(selectUserInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        List<Map<String, Object>> resultList = getDataSourceService().getJdbcTemplate().query(selectUserInfoSql.toString(), new HashMap<>(), new MyColumnMapRowMapper());
//        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(resultList));
//        if (objects.size() > 1) {
//            log.info("根据产品人员信息username查询同步人员信息view_user_eac表结果大于1,username:{}", username);
//        }
        if (CollectionUtils.isNotEmpty(resultList)) {
            zw = MapUtils.getString(resultList.get(0), "zw", "");
        } else {
            log.info("根据产品人员信息username查询同步人员信息view_user_eac表结果为0,username:{}", username);
        }

        data.put("employeeNo", user.getUserId());
        data.put("rank", zw);
        data.put("name", name);
        //xmb 所属项目部/分中心 默认一级部门
        OrganizationFacade organizationFacade = getDubboConfigService().getOrganizationFacade();
        ArrayList<String> departmentIdList = new ArrayList<>();
        getDepartments(organizationFacade, user.getDepartmentId(), departmentIdList);
        String yjbmDepartmentId = "";
        if (departmentIdList.size() >= 2) {
            yjbmDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
        } else if (departmentIdList.size() == 1) {
            yjbmDepartmentId = departmentIdList.get(0);
        }
        DepartmentModel yjbmDepartment = organizationFacade.getDepartment(yjbmDepartmentId, false);
        ArrayList<Map<String, Object>> xmbArray = new ArrayList<>();
        HashMap<String, Object> xmb = new HashMap<>();
        xmb.put("employees", yjbmDepartment.getEmployees());
        xmb.put("id", yjbmDepartment.getId());
        xmb.put("leaf", yjbmDepartment.getLeaf());
        xmb.put("name", yjbmDepartment.getName());
        xmb.put("type", 1);
        xmbArray.add(xmb);
        data.put("xmb", xmbArray);


        //2022-05-03 szdw 所在单位由部门单选改为单行文本，改为部门单选
        //将查询到的一级部门再根据【虚拟部门配置】deptinfo查询虚拟部门
        //如果查到虚拟部门，那么所在单位即为该虚拟部门
        //如果查不到虚拟部门，那么所在单位即为一级部门
        data.put("szdw", null);
        BizObjectQueryModel deptinfoQueryModel = new BizObjectQueryModel();
        deptinfoQueryModel.setSchemaCode("deptinfo");
        deptinfoQueryModel.setQueryCode("deptinfo");
        deptinfoQueryModel.setPageable(new PageableImpl(0, 20));
        FilterExpression.Item it = Q.it("stbm", FilterExpression.Op.Like, yjbmDepartment.getId());
        deptinfoQueryModel.setFilterExpr(it);
        Page<BizObjectModel> deptInfoPage = bizObjectFacade.queryBizObjects(deptinfoQueryModel);
        if (deptInfoPage.getContent().size() > 0) {
            ArrayList<SelectionValue> xnbmList = (ArrayList<SelectionValue>) deptInfoPage.getContent().get(0).get("xnbm");
            if (!ObjectUtils.isEmpty(xnbmList) && xnbmList.size() > 0) {
                ArrayList<SelectionValue> szdwList = new ArrayList<SelectionValue>();
                szdwList.add(xnbmList.get(0));
                data.put("szdw", szdwList);
            }
        } else {
            data.put("szdw", xmbArray);
            data.put("xmb", null);
        }
        return getOkResponseResult(data, "success");
    }

    private DataSourceService getDataSourceService() {
        String dbConnPoolCode = "zcOrgDb";
        BizDatabaseConnectionPool connectionPool = this.connectionPoolService.getByCode(dbConnPoolCode);

        if (connectionPool == null) {
            throw new ServiceException(ErrCode.BIZ_DATA_BASE_POOL_CODE_INVALID, "数据库连接池编码无效");
        } else {
            String datasourceType = connectionPool.getDatasourceType();
            String databaseType = connectionPool.getDatabaseType();
            String type = datasourceType + "." + databaseType;
            DataSourceService dataSourceService = (DataSourceService) TemplateDynamicMultiDataSource.getDataSourceService(dbConnPoolCode, type, JSON.toJSONString(connectionPool));
            return dataSourceService;
        }

    }

    @GetMapping("/kcsbPageAddChange")
    public ResponseResult<Map<String, Object>> kcsbPageAddChange(@RequestParam String userId) {

        if (StringUtils.isEmpty(userId)) {
            log.info("接口kcsbPageAddChange的参数userId为空！,userId:{}", userId);
            return getErrResponseResult(null,99999L, "接口kcsbPageAddChange的参数userId为空！");
        }

        Map<String, Object> data = new HashMap<>();
//        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);
        //String employeeNo = user.getEmployeeNo();
        String name = user.getName();
        String username = user.getUsername();

        // 人员职位获取
        String zw = "";
        StringBuilder selectUserInfoSql = new StringBuilder();
        selectUserInfoSql.append("SELECT * FROM view_user_eac WHERE username = '" + username + "';");
//        List<Map<String, Object>> userInfo = entityManager.createNativeQuery(selectUserInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        List<Map<String, Object>> resultList = getDataSourceService().getJdbcTemplate().query(selectUserInfoSql.toString(), new HashMap<>(), new MyColumnMapRowMapper());
//        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(resultList));
//        if (objects.size() > 1) {
//            log.info("根据产品人员信息username查询同步人员信息view_user_eac表结果大于1,username:{}", username);
//        }
        if (CollectionUtils.isNotEmpty(resultList)) {
            zw = MapUtils.getString(resultList.get(0), "zw", "");
        } else {
            log.info("根据产品人员信息username查询同步人员信息view_user_eac表结果为0,username:{}", username);
        }

        data.put("employeeNo", user.getUserId());
        data.put("rank", zw);
        data.put("name", name);
        //xmb 所属项目部/分中心 默认一级部门
        OrganizationFacade organizationFacade = getDubboConfigService().getOrganizationFacade();
        ArrayList<String> departmentIdList = new ArrayList<>();
        getDepartments(organizationFacade, user.getDepartmentId(), departmentIdList);
        String yjbmDepartmentId = "";
        if (departmentIdList.size() >= 2) {
            yjbmDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
        } else if (departmentIdList.size() == 1) {
            yjbmDepartmentId = departmentIdList.get(0);
        }
        DepartmentModel yjbmDepartment = organizationFacade.getDepartment(yjbmDepartmentId, false);
        ArrayList<Map<String, Object>> xmbArray = new ArrayList<>();
        HashMap<String, Object> xmb = new HashMap<>();
        xmb.put("employees", yjbmDepartment.getEmployees());
        xmb.put("id", yjbmDepartment.getId());
        xmb.put("leaf", yjbmDepartment.getLeaf());
        xmb.put("name", yjbmDepartment.getName());
        xmb.put("type", 1);
        xmbArray.add(xmb);
        data.put("xmb", xmbArray);


        //2022-05-03 szdw 所在单位由部门单选改为单行文本，改为部门单选
        //将查询到的一级部门再根据【虚拟部门配置】deptinfo查询虚拟部门
        //如果查到虚拟部门，那么所在单位即为该虚拟部门
        //如果查不到虚拟部门，那么所在单位即为一级部门
        data.put("szdw", null);
        BizObjectQueryModel deptinfoQueryModel = new BizObjectQueryModel();
        deptinfoQueryModel.setSchemaCode("deptinfo");
        deptinfoQueryModel.setQueryCode("deptinfo");
        deptinfoQueryModel.setPageable(new PageableImpl(0, 20));
        FilterExpression.Item it = Q.it("stbm", FilterExpression.Op.Like, yjbmDepartment.getId());
        deptinfoQueryModel.setFilterExpr(it);
        Page<BizObjectModel> deptInfoPage = bizObjectFacade.queryBizObjects(deptinfoQueryModel);
        if (deptInfoPage.getContent().size() > 0) {
            ArrayList<SelectionValue> xnbmList = (ArrayList<SelectionValue>) deptInfoPage.getContent().get(0).get("xnbm");
            if (!ObjectUtils.isEmpty(xnbmList) && xnbmList.size() > 0) {
                ArrayList<SelectionValue> szdwList = new ArrayList<SelectionValue>();
                szdwList.add(xnbmList.get(0));
                data.put("szdw", szdwList);
            }
        } else {
            data.put("szdw", xmbArray);
            data.put("xmb", null);
        }
        return getOkResponseResult(data, "success");
    }

    /**
     * 刷新课程申报表单的所属项目部/分中心和所在单位
     * 旧：所属项目部/分中心  xmb  默认创建人部门
     * 旧：所在单位  szdw  默认一级部门再根据对照表查询虚拟部门
     * <p>
     * 新：项目部数据项  ——> 一级部门
     * 新：单位数据项  ——> 一级部门对应的虚拟部门(一级部门如没有对应的虚拟部门，则将单位字段置为一级部门的数据，将项目部字段置空)
     */
    @Scheduled(cron = "0 0 23 * * ?")//每天晚上23点执行一次
    @GetMapping("/refreshKCSBUserDepartmen")
    public void refreshKCSBUserDepartmen() {
        //xmb 所属项目部/分中心 开发人一级部门
        //szdw 所在单位 开发人所在一级部门去虚拟部门对照表匹配

        //获取所有课程
        int pageSize = 50;
        int pageIndex = 1;
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcsbNew");
        queryModel.setQueryCode("kcsb_all");
        queryModel.setPageable(new PageableImpl(0, 1));
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        long total = page.getTotal();
        long l = total;
        OrganizationFacade organizationFacade = getOrganizationFacade();
        while (l > 0) {
            int start = (pageIndex - 1) * pageSize;
            queryModel.setPageable(new PageableImpl(start, Integer.valueOf(String.valueOf(pageSize))));
            page = getBizObjectFacade().queryBizObjects(queryModel);
            List<? extends BizObjectModel> content = page.getContent();
            for (BizObjectModel bizObjectModel : content) {
                ArrayList<SelectionValue> kczkfrList = (ArrayList<SelectionValue>) bizObjectModel.get("kczkfr");
                SelectionValue selectionValue = kczkfrList.get(0);
                String id = selectionValue.getId();
                UserModel user = organizationFacade.getUser(id);

                //如果用户不存在或者用户的部门id为空，跳过此次循环。
                //为了避免出现表单中的用户被更改为离职状态。获取不到部门，导致下面代码报错
                if (user == null || StringUtils.isBlank(user.getDepartmentId())) {
                    continue;
                }

                //获取所在单位逻辑#######################
                ArrayList<String> departmentIdList = new ArrayList<>();
                getDepartments(organizationFacade, user.getDepartmentId(), departmentIdList);
                //课程主开发人主部门的一级部门部门id
                String yjbmDepartmentId = "";
                if (departmentIdList.size() >= 2) {
                    yjbmDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
                } else if (departmentIdList.size() == 1) {
                    yjbmDepartmentId = departmentIdList.get(0);
                }
                //获取到课程主开发人的一级部门
                DepartmentModel yjbmDepartment = organizationFacade.getDepartment(yjbmDepartmentId, false);
                //所属项目部/分中心——》查询用户的一级部门
                ArrayList<SelectionValue> xmbList = (ArrayList<SelectionValue>) bizObjectModel.get("xmb");
                //2022-05-03 因需求变动，将所属项目部/分中心改为查询用户的一级部门
                if (xmbList == null || xmbList.size() == 0) {
                    SelectionValue xmb = new SelectionValue();
                    xmb.setId(yjbmDepartment.getId());
                    xmb.setName(yjbmDepartment.getName());
                    xmb.setType(UnitType.DEPARTMENT);
                    xmbList = new ArrayList<SelectionValue>();
                    xmbList.add(xmb);
                } else {
                    SelectionValue xmb = xmbList.get(0);
                    xmb.setId(yjbmDepartment.getId());
                    xmb.setName(yjbmDepartment.getName());
                }
                bizObjectModel.put("xmb", xmbList);
                //结束#######################

                //所在单位——》查询用户的一级部门，将查询到的一级部门再根据【虚拟部门配置】deptinfo查询虚拟部门
                //如果查到虚拟部门，那么所在单位即为该虚拟部门
                //如果查不到虚拟部门，那么所在单位即为一级部门
                BizObjectQueryModel deptinfoQueryModel = new BizObjectQueryModel();
                deptinfoQueryModel.setSchemaCode("deptinfo");
                deptinfoQueryModel.setQueryCode("deptinfo");
                deptinfoQueryModel.setPageable(new PageableImpl(0, 20));
                FilterExpression.Item it = Q.it("stbm", FilterExpression.Op.Like, yjbmDepartment.getId());
                deptinfoQueryModel.setFilterExpr(it);
                Page<BizObjectModel> deptInfoPage = bizObjectFacade.queryBizObjects(deptinfoQueryModel);
                if (deptInfoPage.getContent().size() > 0) {
                    ArrayList<SelectionValue> xnbmList = (ArrayList<SelectionValue>) deptInfoPage.getContent().get(0).get("xnbm");
                    if (!ObjectUtils.isEmpty(xnbmList) && xnbmList.size() > 0) {
                        ArrayList<SelectionValue> szdwList = new ArrayList<SelectionValue>();
                        szdwList.add(xnbmList.get(0));
                        bizObjectModel.put("szdw", szdwList);
                    }
                } else {
                    //如果用户的一级部门在虚拟对照表中找不到，直接把一级部门作为单位
                    bizObjectModel.put("szdw", xmbList);
                    bizObjectModel.put("xmb", null);
                }
                //结束

                getBizObjectFacade().saveBizObject(user.getId(), bizObjectModel, false);
            }
            l = l - pageSize;
            pageIndex = pageIndex + 1;
        }

    }

    /**
     * 刷新入库清单表单的所属项目部/分中心和所在单位
     * 旧：所属项目部/分中心  xmb  默认创建人部门
     * 旧：所在单位  szdw  默认一级部门再根据对照表查询虚拟部门
     * <p>
     * 新：项目部数据项  ——> 一级部门
     * 新：单位数据项  ——> 一级部门对应的虚拟部门(一级部门如没有对应的虚拟部门，则将单位字段置为一级部门的数据，将项目部字段置空)
     */
    @Scheduled(cron = "0 0 23 * * ?")//每天晚上十点执行一次
    @GetMapping("/refreshRKQDUserDepartmen")
    public void refreshRKQDUserDepartmen() {
        //xmb 所属项目部/分中心 开发人一级部门
        //szdw 所在单位 开发人所在一级部门去虚拟部门对照表匹配

        //获取所有课程
        int pageSize = 50;
        int pageIndex = 1;
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcqd");
        queryModel.setQueryCode("kcsb_all");
        queryModel.setPageable(new PageableImpl(0, 1));
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        long total = page.getTotal();
        long l = total;
        OrganizationFacade organizationFacade = getOrganizationFacade();
        while (l > 0) {
            int start = (pageIndex - 1) * pageSize;
            queryModel.setPageable(new PageableImpl(start, Integer.valueOf(String.valueOf(pageSize))));
            page = getBizObjectFacade().queryBizObjects(queryModel);
            List<? extends BizObjectModel> content = page.getContent();
            for (BizObjectModel bizObjectModel : content) {
                ArrayList<SelectionValue> kczkfrList = (ArrayList<SelectionValue>) bizObjectModel.get("kczkfr");
                SelectionValue selectionValue = kczkfrList.get(0);
                String id = selectionValue.getId();
                UserModel user = organizationFacade.getUser(id);

                //如果用户不存在或者用户的部门id为空，跳过此次循环。
                //为了避免出现表单中的用户被更改为离职状态。获取不到部门，导致下面代码报错
                if (user == null || StringUtils.isBlank(user.getDepartmentId())) {
                    continue;
                }

                //获取所在单位逻辑#######################
                ArrayList<String> departmentIdList = new ArrayList<>();
                getDepartments(organizationFacade, user.getDepartmentId(), departmentIdList);
                //课程主开发人主部门的一级部门部门id
                String yjbmDepartmentId = "";
                if (departmentIdList.size() >= 2) {
                    yjbmDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
                } else if (departmentIdList.size() == 1) {
                    yjbmDepartmentId = departmentIdList.get(0);
                }
                //获取到课程主开发人的一级部门
                DepartmentModel yjbmDepartment = organizationFacade.getDepartment(yjbmDepartmentId, false);
                //所属项目部/分中心——》查询用户的一级部门
                ArrayList<SelectionValue> xmbList = (ArrayList<SelectionValue>) bizObjectModel.get("xmb");
                //2022-05-03 因需求变动，将所属项目部/分中心改为查询用户的一级部门
                if (xmbList == null || xmbList.size() == 0) {
                    SelectionValue xmb = new SelectionValue();
                    xmb.setId(yjbmDepartment.getId());
                    xmb.setName(yjbmDepartment.getName());
                    xmb.setType(UnitType.DEPARTMENT);
                    xmbList = new ArrayList<SelectionValue>();
                    xmbList.add(xmb);
                } else {
                    SelectionValue xmb = xmbList.get(0);
                    xmb.setId(yjbmDepartment.getId());
                    xmb.setName(yjbmDepartment.getName());
                }
                bizObjectModel.put("xmb", xmbList);

                //所在单位——》查询用户的一级部门，将查询到的一级部门再根据【虚拟部门配置】deptinfo查询虚拟部门
                //如果查到虚拟部门，那么所在单位即为该虚拟部门
                //如果查不到虚拟部门，那么所在单位即为一级部门
                BizObjectQueryModel deptinfoQueryModel = new BizObjectQueryModel();
                deptinfoQueryModel.setSchemaCode("deptinfo");
                deptinfoQueryModel.setQueryCode("deptinfo");
                deptinfoQueryModel.setPageable(new PageableImpl(0, 20));
                FilterExpression.Item it = Q.it("stbm", FilterExpression.Op.Like, yjbmDepartment.getId());
                deptinfoQueryModel.setFilterExpr(it);
                Page<BizObjectModel> deptInfoPage = bizObjectFacade.queryBizObjects(deptinfoQueryModel);
                if (deptInfoPage.getContent().size() > 0) {
                    ArrayList<SelectionValue> xnbmList = (ArrayList<SelectionValue>) deptInfoPage.getContent().get(0).get("xnbm");
                    if (!ObjectUtils.isEmpty(xnbmList) && xnbmList.size() > 0) {
                        ArrayList<SelectionValue> szdwList = new ArrayList<SelectionValue>();
                        szdwList.add(xnbmList.get(0));
                        bizObjectModel.put("szdw", szdwList);
                    }
                } else {
                    //如果用户的一级部门在虚拟对照表中找不到，直接把一级部门作为单位
                    bizObjectModel.put("szdw", xmbList);
                    bizObjectModel.put("xmb", null);
                }
                //结束
                getBizObjectFacade().saveBizObject(user.getId(), bizObjectModel, false);
            }
            l = l - pageSize;
            pageIndex = pageIndex + 1;
        }

    }

    /**
     * 刷新讲师库管理
     * 单位 dw 单行文本
     * 部门 bm 单行文本
     * 所属项目部/分中心  xmb  默认创建人部门
     * 所在单位  szdw  默认一级部门再根据对照表查询虚拟部门
     */
    @Scheduled(cron = "0 0 23 * * ?")//每天晚上十点执行一次
    @GetMapping("/refreshJskgl")
    public void refreshJskgl() {
        int pageSize = 50;
        int pageIndex = 1;
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("jskgl");
        queryModel.setQueryCode("jskgl");
        queryModel.setPageable(new PageableImpl(0, 1));
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        long total = page.getTotal();
        long l = total;
        OrganizationFacade organizationFacade = getOrganizationFacade();
        while (l > 0) {
            int start = (pageIndex - 1) * pageSize;
            queryModel.setPageable(new PageableImpl(start, Integer.valueOf(String.valueOf(pageSize))));
            page = getBizObjectFacade().queryBizObjects(queryModel);
            List<? extends BizObjectModel> content = page.getContent();
            for (BizObjectModel bizObjectModel : content) {
                //通过xm姓名，获取讲师信息
                ArrayList<SelectionValue> xmList = (ArrayList<SelectionValue>) bizObjectModel.get("xm");
                SelectionValue selectionValue = xmList.get(0);
                String id = selectionValue.getId();
                UserModel user = organizationFacade.getUser(id);

                //如果用户不存在或者用户的部门id为空，跳过此次循环。
                //为了避免出现表单中的用户被更改为离职状态。获取不到部门，导致下面代码报错
                if (user == null || StringUtils.isBlank(user.getDepartmentId())) {
                    continue;
                }

                //bm 获取部门 参考之前入库课程清单的逻辑，默认一级部门
                ArrayList<String> departmentIdList = new ArrayList<>();
                getDepartments(organizationFacade, user.getDepartmentId(), departmentIdList);
                String xmbDepartmentId = "";
                if (departmentIdList.size() >= 2) {
                    xmbDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
                } else if (departmentIdList.size() == 1) {
                    xmbDepartmentId = departmentIdList.get(0);
                }
                DepartmentModel bm = organizationFacade.getDepartment(xmbDepartmentId, false);
                bizObjectModel.put("bm", bm.getName());


                //获取dw单位
                String dwDepartmentId = "";
                if (departmentIdList.size() >= 2) {
                    dwDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
                } else if (departmentIdList.size() == 1) {
                    dwDepartmentId = departmentIdList.get(0);
                }
                DepartmentModel dwDepartment = organizationFacade.getDepartment(dwDepartmentId, false);
                //将查询到的一级部门再根据【虚拟部门配置】deptinfo查询虚拟部门
                BizObjectQueryModel deptinfoQueryModel = new BizObjectQueryModel();
                deptinfoQueryModel.setSchemaCode("deptinfo");
                deptinfoQueryModel.setQueryCode("deptinfo");
                deptinfoQueryModel.setPageable(new PageableImpl(0, 20));
                FilterExpression.Item it = Q.it("stbm", FilterExpression.Op.Like, dwDepartment.getId());
                deptinfoQueryModel.setFilterExpr(it);
                Page<BizObjectModel> deptInfoPage = bizObjectFacade.queryBizObjects(deptinfoQueryModel);
                if (deptInfoPage.getContent().size() > 0) {
                    ArrayList<SelectionValue> xnbmList = (ArrayList<SelectionValue>) deptInfoPage.getContent().get(0).get("xnbm");
                    if (!ObjectUtils.isEmpty(xnbmList) && xnbmList.size() > 0) {
                        SelectionValue selectionValue1 = xnbmList.get(0);
                        bizObjectModel.put("dw", selectionValue1.getName());
                    }
                } else {
                    //如果用户的一级部门在虚拟对照表中找不到，直接把一级部门作为单位，并且把部门置空
                    bizObjectModel.put("dw", bm.getName());
                    bizObjectModel.put("bm", null);
                }


                //获取zw职位
                String zw = "";
                String username = user.getUsername();
                StringBuilder selectUserInfoSql = new StringBuilder();
                selectUserInfoSql.append("SELECT * FROM view_user_eac WHERE username = '" + username + "';");
                List<Map<String, Object>> resultList = getDataSourceService().getJdbcTemplate().query(selectUserInfoSql.toString(), new HashMap<>(), new MyColumnMapRowMapper());
                log.info("查询视图返回resultList:{}", resultList);
                if (CollectionUtils.isNotEmpty(resultList)) {
                    zw = MapUtils.getString(resultList.get(0), "zw", "");
                } else {
                    log.info("根据产品人员信息username查询同步人员信息view_user_eac表结果为0,username:{}", username);
                }
                bizObjectModel.put("zw", zw);


                ////获取cjgzsj参加工作时间
                //String gzsj = "";
                //if (CollectionUtils.isNotEmpty(resultList)) {
                //    bizObjectModel.put("prsj", resultList.get(0).get("gzsj"));
                //} else {
                //    log.info("根据产品人员信息username查询同步人员信息view_user_eac表结果为0,username:{}", username);
                //}
                ArrayList<SelectionValue> createrList = (ArrayList<SelectionValue>) bizObjectModel.get("creater");
                getBizObjectFacade().saveBizObject(createrList.get(0).getId(), bizObjectModel, false);
            }
            l = l - pageSize;
            pageIndex = pageIndex + 1;
        }
    }

    public static void getDepartments(OrganizationFacade organizationFacade, String departmentId, List<String> departmentIdList) {
        DepartmentModel department = organizationFacade.getDepartment(departmentId, false);
        departmentIdList.add(departmentId);
        if (department != null && StringUtils.isNotBlank(department.getParentId())) {
            //继续往上查找父部门
            getDepartments(organizationFacade, department.getParentId(), departmentIdList);
        }
    }

    /**
     * 刷新活动通知流程表单的所属项目部/分中心和所在单位
     * 所属项目部/分中心 ——> 一级部门
     * 单位 ——> 一级部门对应的虚拟部门(一级部门如没有对应的虚拟部门，则将单位字段置为一级部门的数据，将项目部字段置空)
     * 工号 ——> user模型中获取
     */
    @Scheduled(cron = "0 0 23 * * ?")//每天晚上23点执行一次
    @GetMapping("/refreshHDTZLC")
    public void refreshHDTZLC() {
        int pageSize = 50;
        int pageIndex = 1;
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("hdtzlc");
        queryModel.setQueryCode("hdtzlc");
        queryModel.setPageable(new PageableImpl(0, 1));
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        long total = page.getTotal();
        long l = total;
        OrganizationFacade organizationFacade = getOrganizationFacade();
        while (l > 0) {
            int start = (pageIndex - 1) * pageSize;
            queryModel.setPageable(new PageableImpl(start, Integer.valueOf(String.valueOf(pageSize))));
            page = getBizObjectFacade().queryBizObjects(queryModel);
            List<? extends BizObjectModel> content = page.getContent();
            for (BizObjectModel bizObjectModel : content) {
                //通过xm姓名，获取讲师信息
                ArrayList<SelectionValue> createrList = (ArrayList<SelectionValue>) bizObjectModel.get("creater");
                SelectionValue selectionValue = createrList.get(0);
                String id = selectionValue.getId();
                UserModel user = organizationFacade.getUser(id);

                //如果用户不存在或者用户的部门id为空，跳过此次循环。
                //为了避免出现表单中的用户被更改为离职状态。获取不到部门，导致下面代码报错
                if (user == null || StringUtils.isBlank(user.getDepartmentId())) {
                    continue;
                }

                //userId为用户的工号
                String gongHao = user.getUserId();

                //获取 所属项目部/分中心 逻辑#######################
                ArrayList<String> departmentIdList = new ArrayList<>();
                getDepartments(organizationFacade, user.getDepartmentId(), departmentIdList);
                //表单创建人主部门往上找到一级部门的部门id
                String yjbmDepartmentId = "";
                if (departmentIdList.size() >= 2) {
                    yjbmDepartmentId = departmentIdList.get(departmentIdList.size() - 2);
                } else if (departmentIdList.size() == 1) {
                    yjbmDepartmentId = departmentIdList.get(0);
                }
                //获取到课程主开发人的一级部门
                DepartmentModel yjbmDepartment = organizationFacade.getDepartment(yjbmDepartmentId, false);
                //所属项目部/分中心——》查询用户的一级部门
                ArrayList<SelectionValue> xmbList = (ArrayList<SelectionValue>) bizObjectModel.get("xmb");
                //2022-05-03 因需求变动，将所属项目部/分中心改为查询用户的一级部门
                if (xmbList == null || xmbList.size() == 0) {
                    SelectionValue xmb = new SelectionValue();
                    xmb.setId(yjbmDepartment.getId());
                    xmb.setName(yjbmDepartment.getName());
                    xmb.setType(UnitType.DEPARTMENT);
                    xmbList = new ArrayList<SelectionValue>();
                    xmbList.add(xmb);
                } else {
                    SelectionValue xmb = xmbList.get(0);
                    xmb.setId(yjbmDepartment.getId());
                    xmb.setName(yjbmDepartment.getName());
                }
                bizObjectModel.put("xmb", xmbList);
                //部门的单行文本 bm
                bizObjectModel.put("bm", xmbList.get(0).getName());

                //所在单位——》查询用户的一级部门，将查询到的一级部门再根据【虚拟部门配置】deptinfo查询虚拟部门
                //如果查到虚拟部门，那么所在单位即为该虚拟部门
                //如果查不到虚拟部门，那么所在单位即为一级部门
                BizObjectQueryModel deptinfoQueryModel = new BizObjectQueryModel();
                deptinfoQueryModel.setSchemaCode("deptinfo");
                deptinfoQueryModel.setQueryCode("deptinfo");
                deptinfoQueryModel.setPageable(new PageableImpl(0, 20));
                FilterExpression.Item it = Q.it("stbm", FilterExpression.Op.Like, yjbmDepartment.getId());
                deptinfoQueryModel.setFilterExpr(it);
                Page<BizObjectModel> deptInfoPage = bizObjectFacade.queryBizObjects(deptinfoQueryModel);
                if (deptInfoPage.getContent().size() > 0) {
                    ArrayList<SelectionValue> xnbmList = (ArrayList<SelectionValue>) deptInfoPage.getContent().get(0).get("xnbm");
                    if (!ObjectUtils.isEmpty(xnbmList) && xnbmList.size() > 0) {
                        ArrayList<SelectionValue> szdwList = new ArrayList<SelectionValue>();
                        szdwList.add(xnbmList.get(0));
                        bizObjectModel.put("szdw", szdwList);
                        //单位的单行文本 dw
                        bizObjectModel.put("dw", szdwList.get(0).getName());
                    }
                } else {
                    //如果用户的一级部门在虚拟对照表中找不到，直接把一级部门作为单位
                    bizObjectModel.put("szdw", xmbList);
                    bizObjectModel.put("xmb", null);
                    //单位的单行文本 dw
                    bizObjectModel.put("dw", xmbList.get(0).getName());
                    //部门的单行文本 bm
                    bizObjectModel.put("bm", null);
                }
                bizObjectModel.put("gonghao", gongHao);
                getBizObjectFacade().saveBizObject(createrList.get(0).getId(), bizObjectModel, false);
            }
            l = l - pageSize;
            pageIndex = pageIndex + 1;
        }
    }

    /**
     * 根据活动级别获取活动业务路线（取数据表当前业务节点，推进数据表当前业务节点，记录日志）
     *
     * @param hdjb
     * @return
     */
    @GetMapping("/businessLine")
    @Transactional
    public ResponseResult<String> businessLine(@RequestParam(required = false) String hdjb,
                                               @RequestParam(required = false) String dqyw,
                                               @RequestParam String kcsbId,
                                               @RequestParam(required = false) String fallBack,
                                               @RequestParam String buttonMark,
                                               @RequestParam(required = false) String opinion) {

        // 业务路线
        String ywlx = "Undefined";

        // 如果参数传入活动级别，则依据活动级别获取业务路线
        if (StringUtils.isNotEmpty(hdjb)) {
            String ywxlTableName = getBizObjectFacade().getTableName("ywxlNew");
            StringBuilder selectBusinessLineSql = new StringBuilder();
            selectBusinessLineSql.append("SELECT T.ywlx FROM `" + ywxlTableName + "` T WHERE T.xlmc = '" + hdjb + "'");
            ywlx = (String) entityManager.createNativeQuery(selectBusinessLineSql.toString()).getSingleResult();
        }

        String msg = "Undefined";

        String denied = "驳回修改";
        String pass = "通过";

        // 课程申报
        String kcsb = "kcsb";
        // 基层信息审核
        String jcxxsh = "jcxxsh";
        // 基层评审推荐审批
        String jcpstjSp = "jcpstjSp";
        // 基层评审推荐
        String jcpstj = "jcpstj";
        // 中心审核
        String zxsh = "zxsh";
        // 中心初评
        String zxcp = "zxcp";
        // 中心终评
        String zxzp = "zxzp";
        // 试讲管理
        String sjgl = "sjgl";
        // 结果确认与发布
        String jgqryfb = "jgqryfb";

        String[] splitID = kcsbId.split(";");

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");

        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);

        if (kcsb.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【课程申报】逻辑");
            // 课程申报
            for (int j = 0; j < splitID.length; j++) {
                log.info("\n===========进入【业务路线】方法【课程申报】逻辑【通过】逻辑,评审汇总id={}", splitID[j]);
                // 通过
//                StringBuilder updateDQYWsql = new StringBuilder();
//                updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_JCXXSH = '" + "jcxxsh" + "', T.Dropdown_JCXXSH = '待办' WHERE T.id = '" + splitID[j] + "'");
//                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
//                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
//                msg = "更新数据条数" + updateNum;
                // 记录日志到表单
                logAdd("发起课程申报", "信息审核", splitID[j], user.getName(), userId, true);
            }
        } else if (jcxxsh.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【基层信息审核】逻辑");
            // 基层信息审核
            for (int j = 0; j < splitID.length; j++) {
//                StringBuilder selectCourseInfoSql = new StringBuilder();
//                selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
//                // 根据ID取得课程申报信息
//                List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//                String shjg = MapUtils.getString(resultList.get(0), "shjg");
                if (StringUtils.isNotEmpty(fallBack) && fallBack.equals(denied)) {
                    // 驳回修改
                    StringBuilder updateDQYWsql = new StringBuilder();
                    Map step = nextStep(splitID[j], true, ywlx, 0);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    if (StringUtils.isEmpty(nextStep)) {
                        // 暂为整个业务首个节点，因此驳回操作相同
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_JCXXSH = '待办' WHERE T.id = '" + splitID[j] + "'");
                    } else {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_JCXXSH = null , T.Dropdown_JCXXSH = '待办', T.shjg = null WHERE T.id = '" + splitID[j] + "'");
                    }
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    // 发起驳回流程
                    sendRejectMessage(splitID[j], "基层信息审核", opinion);
                    // 记录日志到表单
                    logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, true);
                    msg = "更新数据条数" + updateNum;
                } else if (StringUtils.isNotEmpty(fallBack) && fallBack.equals(pass)) {
                    // 通过
                    StringBuilder updateDQYWsql = new StringBuilder();
                    Map step = nextStep(splitID[j], false, ywlx, 0);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    if (StringUtils.isEmpty(nextStep)) {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_JCXXSH = '已办' WHERE T.id = '" + splitID[j] + "'");
                    } else {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_JCPSTJ = '" + "jcpstj" + "', T.Dropdown_JCPSTJ = '待办' , T.Dropdown_JCXXSH = '已办', T.ShortTextDQYW = '" + nextStep + "' WHERE T.id = '" + splitID[j] + "'");
                    }
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                    msg = "更新数据条数" + updateNum;
                } else {
                    Map step = nextStep(splitID[j], false, ywlx, 1);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    // 不通过
                    StringBuilder updateDQYWsql = new StringBuilder();
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_JCXXSH = '已办' WHERE T.id = '" + splitID[j] + "'");
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    logAdd(dqywRes, dqywRes, splitID[j], user.getName(), userId, false);
                    msg = "更新数据条数" + updateNum;
                }
            }
        } else if (jcpstjSp.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【基层评审推荐审批】逻辑");
            // 基层评审推荐审批
            Map<String, Map<String, Object>> fMap = new HashMap<>();
            for (int j = 0; j < splitID.length; j++) {

                Map step = nextStep(splitID[j], false, ywlx, 1);
                String nextStep = MapUtils.getString(step, "nextStep");
                String dqywRes = MapUtils.getString(step, "dqyw");

                StringBuilder selectCourseInfoSql = new StringBuilder();
                selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
                // 根据ID取得课程申报信息
                List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();

                // 活动ID
                String sbhdId = (String) resultList.get(0).get("RelevanceFormSBHD");
                StringBuilder getHdmcByIdSql = new StringBuilder();
                String sbhdNewTableName = getBizObjectFacade().getTableName("sbhdNew");
                getHdmcByIdSql.append("SELECT * FROM `" + sbhdNewTableName + "` T WHERE T.id = '" + sbhdId + "'");
                List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                String hdmcId = (String) hdmcList.get(0).get("id");
                String hdmc = (String) hdmcList.get(0).get("hdmc");
                // 获取发起活动的部门
                DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
                if (!fMap.containsKey(hdmcId)) {
                    // 新增活动单位
                    Map<String, Object> smap = new HashMap<>();
                    // 子表
                    smap.put("SheetInfo", new ArrayList<>());
                    // 子表
                    smap.put("Sheet_kcsqlb", new ArrayList<>());
                    // 活动名称_发起人一级部门
                    smap.put("SText_actvNameAndDeptLevOne", hdmc + "_" + dept.getName());
                    // 审批结果
                    smap.put("Dropdown_spjg", "");
                    fMap.put(hdmcId, smap);
                }
                Map<String, Object> dqHdmc = fMap.get(hdmcId);
                List courseList = (List) dqHdmc.get("SheetInfo");
                List courseListTwo = (List) dqHdmc.get("Sheet_kcsqlb");
                Map<String, Object> courseInfo = new HashMap<>();
                Map<String, Object> courseInfoTwo = new HashMap<>();
                // 课程ID
                courseInfo.put("ShortTextCourseID", resultList.get(0).get("id"));
                courseInfoTwo.put("ShortTextCourseID", resultList.get(0).get("id"));
                // 工号
                courseInfo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
                courseInfoTwo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
                // 姓名
                courseInfo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
                courseInfoTwo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
                // 课程/案例名称
                courseInfo.put("SText_caseName", resultList.get(0).get("courseName"));
                courseInfoTwo.put("SText_caseName", resultList.get(0).get("courseName"));
                // 推荐结果
                courseInfo.put("ShortText_marketing", resultList.get(0).get("tjjg"));
                courseInfoTwo.put("ShortText_marketing", resultList.get(0).get("tjjg"));
                // 审批状态
                courseInfo.put("ShortText_approvalStatus", resultList.get(0).get("currentAuditstate"));
                // 部门
                courseInfo.put("ShortText_departLevelTwo", resultList.get(0).get("xmb"));
                // 单位
                courseInfo.put("ShortText_unit", resultList.get(0).get("szdw"));
                // 课程/案例类别
                courseInfo.put("ShortText_SText_caseType", resultList.get(0).get("category"));
                // 课时
                courseInfo.put("ShortText_spendTime", resultList.get(0).get("classHour"));
                // 培训对象
                courseInfo.put("ShortText_caseTarget", resultList.get(0).get("cultivateObj"));
                // 参与人
                courseInfo.put("StaffMulti_CYR", resultList.get(0).get("tdcy"));
                // 基层评审得分
                courseInfo.put("ShortText_basicScore", resultList.get(0).get("jcpsdf"));
                // 推荐结果
                courseInfo.put("ShortText_basicMarketing", resultList.get(0).get("tjjg"));
                // 审批结果
                courseInfo.put("ShortText_approvalResult", resultList.get(0).get("shjg"));

                courseInfo.put("rowStatus", "Added");
                courseList.add(courseInfo);
                dqHdmc.put("SheetInfo", courseList);
                courseInfoTwo.put("rowStatus", "Added");
                courseListTwo.add(courseInfoTwo);
                dqHdmc.put("Sheet_kcsqlb", courseListTwo);
                dqHdmc.put("Dropdown_spjg", "审批通过");
                fMap.put(hdmcId, dqHdmc);

                // 设定列表审批状态
                StringBuilder updateDQYWsql = new StringBuilder();
                updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set  T.ldspzt = '" + "审批中" + "' WHERE T.id = '" + splitID[j] + "'");
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                logAdd(dqywRes, dqywRes, splitID[j], user.getName(), userId, false);
            }
            for (Map.Entry<String, Map<String, Object>> entry : fMap.entrySet()) {
                Map<String, Object> map = entry.getValue();
                // 发起基层领导审批流程
                BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("DepartmentLeaderApproval", map, false);
                String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
                String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "deptManagerApproveFlow", bizObjectId, true);
                log.info("\n=======基层领导审批流程发起成功,instanceId={}", instanceId);
                msg = "审批流程id:" + instanceId;
            }
        } else if (jcpstj.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【基层评审推荐】逻辑");
            // 基层评审推荐
            for (int j = 0; j < splitID.length; j++) {
                // 通过
                StringBuilder updateDQYWsql = new StringBuilder();
                Map step = nextStep(splitID[j], false, ywlx, 1);
                String nextStep = MapUtils.getString(step, "nextStep");
                String dqywRes = MapUtils.getString(step, "dqyw");
                if (StringUtils.isEmpty(nextStep)) {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_JCPSTJ = '已办', T.ShortTextDQYW = '" + "结束" + "', T.ldspzt = '" + "已推荐" + "' WHERE T.id = '" + splitID[j] + "'");
                } else {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_ZXSH = '" + "zxsh" + "', T.Dropdown_ZXSH = '待办', T.Dropdown_JCPSTJ = '已办', T.shjgZx = null, T.ShortTextDQYW = '" + nextStep + "', T.ldspzt = '" + "已推荐" + "', T.zxshFbzt = null WHERE T.id = '" + splitID[j] + "'");
                }
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                msg = "更新数据条数" + updateNum;
            }
        } else if (zxsh.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【中心审核】逻辑");
            // 中心审核
            for (int j = 0; j < splitID.length; j++) {
                StringBuilder selectCourseInfoSql = new StringBuilder();
                selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
                // 根据ID取得课程申报信息
                List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                String shjgZX = MapUtils.getString(resultList.get(0), "shjgZx", "通过");
                if (StringUtils.isNotEmpty(shjgZX) && shjgZX.equals(denied)) {
                    // 驳回修改
                    StringBuilder updateDQYWsql = new StringBuilder();
                    Map step = nextStep(splitID[j], true, ywlx, 1);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    if (StringUtils.isEmpty(nextStep)) {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXSH = '待办', T.zxshFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                    } else {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXSH = '待办', T.Dropdown_JCPSTJ = '待办', T.ShortTextDQYW = '" + nextStep + "', T.ldspzt = null, T.zxshFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                    }
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    // 发起驳回流程
                    sendRejectMessage(splitID[j], "中心审核", opinion);
                    logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, true);
                    msg = "更新数据条数" + updateNum;
                } else if (StringUtils.isNotEmpty(shjgZX) && shjgZX.equals(pass)) {
                    // 通过
                    StringBuilder updateDQYWsql = new StringBuilder();
                    Map step = nextStep(splitID[j], false, ywlx, 0);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    if (StringUtils.isEmpty(nextStep)) {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXSH = '已办', T.zxshFbzt = '" + "已发布" + "', T.shjgZx = '通过' WHERE T.id = '" + splitID[j] + "'");
                    } else {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_ZXCP = '" + "zxcp" + "', T.Dropdown_ZXCP = '待办', T.Dropdown_ZXSH = '已办', T.ShortTextDQYW = '" + nextStep + "', T.zxshFbzt = '" + "已发布" + "', T.shjgZx = '通过' WHERE T.id = '" + splitID[j] + "'");
                    }
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                    msg = "更新数据条数" + updateNum;
                } else {
                    Map step = nextStep(splitID[j], false, ywlx, 0);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    // 不通过
                    StringBuilder updateDQYWsql = new StringBuilder();
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXSH = '已办' WHERE T.id = '" + splitID[j] + "'");
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    logAdd(dqywRes, dqywRes, splitID[j], user.getName(), userId, false);
                    msg = "更新数据条数" + updateNum;
                }
            }
        } else if (zxcp.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【中心初评】逻辑");
            // 中心初评
            for (int j = 0; j < splitID.length; j++) {
                // 通过
                StringBuilder updateDQYWsql = new StringBuilder();
                Map step = nextStep(splitID[j], false, ywlx, 0);
                String nextStep = MapUtils.getString(step, "nextStep");
                String dqywRes = MapUtils.getString(step, "dqyw");
                if (StringUtils.isEmpty(nextStep)) {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXCP = '已办', T.zxcpFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                } else {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_ZXZP = '" + "zxzp" + "', T.Dropdown_ZXZP = '待办', T.Dropdown_ZXCP = '已办', T.ShortTextDQYW = '" + nextStep + "', T.zxcpFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                }
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                msg = "更新数据条数" + updateNum;
            }
        } else if (zxzp.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【中心终评】逻辑");
            // 中心终评
            for (int j = 0; j < splitID.length; j++) {
                StringBuilder selectCourseInfoSql = new StringBuilder();
                selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
                // 根据ID取得课程申报信息
                List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                // 课程分类
                String hdlb = MapUtils.getString(resultList.get(0), "hdlb");
                // 课程等级
                String kcdj = MapUtils.getString(resultList.get(0), "kcdj");
                if (StringUtils.isNotEmpty(hdlb) && StringUtils.isNotEmpty(kcdj) && hdlb.contains("面授") && kcdj.contains("精品")) {
                    // 通过
                    StringBuilder updateDQYWsql = new StringBuilder();
                    Map step = nextStep(splitID[j], false, ywlx, 0);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    if (StringUtils.isEmpty(nextStep)) {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXZP = '已办', T.zxzpFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                    } else {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_SJGL = '" + "sjgl" + "', T.Dropdown_SJGL = '待办', T.Dropdown_ZXZP = '已办', T.ShortTextDQYW = '" + nextStep + "', T.zxzpFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                    }
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                    msg = "更新数据条数" + updateNum;
                } else {
                    // 通过
                    StringBuilder updateDQYWsql = new StringBuilder();
                    Map step = nextStep(splitID[j], false, ywlx, 1);
                    String nextStep = MapUtils.getString(step, "nextStep");
                    String dqywRes = MapUtils.getString(step, "dqyw");
                    if (StringUtils.isEmpty(nextStep)) {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_ZXZP = '已办', T.zxzpFbzt = '" + "已发布" + "', T.ShortTextDQYW = '" + "结束" + "' WHERE T.id = '" + splitID[j] + "'");
                    } else {
                        updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_JGQRYFB = '" + "jgqryfb" + "', T.Dropdown_JGQRYFB = '待办', T.Dropdown_ZXZP = '已办', T.ShortTextDQYW = '" + nextStep + "', T.zxzpFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                    }
                    int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                    log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                    logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                    msg = "更新数据条数" + updateNum;
                }
            }
        } else if (sjgl.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【试讲管理】逻辑");
            // 试讲管理
            for (int j = 0; j < splitID.length; j++) {
                // 通过
                StringBuilder updateDQYWsql = new StringBuilder();
                Map step = nextStep(splitID[j], false, ywlx, 0);
                String nextStep = MapUtils.getString(step, "nextStep");
                String dqywRes = MapUtils.getString(step, "dqyw");
                if (StringUtils.isEmpty(nextStep)) {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_SJGL = '已办', T.sjglTjzt = '" + "已提交" + "' WHERE T.id = '" + splitID[j] + "'");
                } else {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortText_JGQRYFB = '" + "jgqryfb" + "', T.Dropdown_JGQRYFB = '待办', T.Dropdown_SJGL = '已办', T.ShortTextDQYW = '" + nextStep + "', T.sjglTjzt = '" + "已提交" + "' WHERE T.id = '" + splitID[j] + "'");
                }
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                msg = "更新数据条数" + updateNum;
            }
        } else if (jgqryfb.equals(buttonMark)) {
            log.info("\n===========进入【业务路线】方法【结果确认与发布】逻辑");
            // 结果确认与发布
            for (int j = 0; j < splitID.length; j++) {
                // 通过
                StringBuilder updateDQYWsql = new StringBuilder();
                Map step = nextStep(splitID[j], false, ywlx, 0);
                String nextStep = MapUtils.getString(step, "nextStep");
                String dqywRes = MapUtils.getString(step, "dqyw");
                if (StringUtils.isEmpty(nextStep)) {
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_JGQRYFB = '已办', T.ShortTextDQYW = '" + "结束" + "', T.jgqryFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                } else {
                    // 暂为整个业务最终节点，因此通过操作相同
                    updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.Dropdown_JGQRYFB = '已办', T.jgqryFbzt = '" + "已发布" + "' WHERE T.id = '" + splitID[j] + "'");
                }
                int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
                log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
                logAdd(dqywRes, nextStep, splitID[j], user.getName(), userId, false);
                msg = "更新数据条数" + updateNum;
            }
        } else {
            msg = "业务流转按钮buttonMark未在定义范围内";
            log.info("===========================业务流转按钮buttonMark未在定义范围内");
        }


//
////        String userId = getUserId();
////        UserModel user = getOrganizationFacade().getUser(userId);
//
//
//
//        boolean useParam = true;
//        // 若业务路线未定义，则未传入活动级别，后续根据id查找业务路线
//        if ("Undefined".equals(ywlx)) {
//            useParam = false;
//        }
//
//
//        Map<String, Map<String, Object>> fMap = new HashMap<>();
//        // 处理传入的id拼接数据
//        for (int j = 0; j < splitID.length; j++) {
//            String subDqyw = "";
//            String subYwlx = "";
//            StringBuilder selectCourseInfoSql = new StringBuilder();
//            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
//            // 根据ID取得课程申报信息
//            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            if (!useParam) {
//                subYwlx = (String) resultList.get(0).get("ShortTextYWLX");
//                subDqyw = (String) resultList.get(0).get("ShortTextDQYW");
//            } else {
//                subYwlx = ywlx;
//                subDqyw = dqyw;
//            }
//            String[] split = subYwlx.split(";");
//            String xyjd = "";
//            String dBdqyw = "";
//            String dBxyjd = "";
//            String userName = user.getName();
//            if (StringUtils.isEmpty(subDqyw)) {
//                subDqyw = split[0];
//                if (split.length < 2) {
//                    xyjd = "done";
//                } else {
//                    xyjd = split[1];
//                }
//            } else {
//                for (int i = 0; i < split.length; i++) {
//                    if (subDqyw.equals(split[i])) {
//                        if (StringUtils.isNotEmpty(fallBack)) {
//                            dBdqyw = subDqyw;
//                            subDqyw = i > 0 ? split[i - 1] : "";
//                            dBxyjd = subDqyw;
//                            xyjd = split[i];
//                        } else {
//                            dBdqyw = subDqyw;
//                            subDqyw = i < split.length - 1 ? split[i + 1] : "done";
//                            dBxyjd = subDqyw;
//                            xyjd = i < split.length - 2 ? split[i + 2] : "done";
//                        }
//                        break;
//                    }
//                }
//                // 若当前节点为审批相关，则发起对应审批流程
//                if (subDqyw.contains("审批")) {
//                    // 活动ID
//                    String sbhdId = (String) resultList.get(0).get("RelevanceFormSBHD");
//                    StringBuilder getHdmcByIdSql = new StringBuilder();
//                    String sbhdNewTableName = getBizObjectFacade().getTableName("sbhdNew");
//                    getHdmcByIdSql.append("SELECT * FROM `" + sbhdNewTableName + "` T WHERE T.id = '" + sbhdId + "'");
//                    List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//                    String hdmcId = (String) hdmcList.get(0).get("id");
//                    String hdmc = (String) hdmcList.get(0).get("hdmc");
//                    // 获取发起活动的部门
//                    DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
//                    if (!fMap.containsKey(hdmcId)) {
//                        // 新增活动单位
//                        Map<String, Object> smap = new HashMap<>();
//                        // 子表
//                        smap.put("SheetInfo", new ArrayList<>());
//                        // 活动名称_发起人一级部门
//                        smap.put("SText_actvNameAndDeptLevOne", hdmc + "_" + dept.getName());
//                        fMap.put(hdmcId, smap);
//                    }
//                    Map<String, Object> dqHdmc = fMap.get(hdmcId);
//                    List courseList = (List) dqHdmc.get("SheetInfo");
//                    Map<String, Object> courseInfo = new HashMap<>();
//                    // 课程ID
//                    courseInfo.put("ShortTextCourseID", resultList.get(0).get("id"));
//                    // 工号
//                    courseInfo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
//                    // 姓名
//                    courseInfo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
//                    // 课程/案例名称
//                    courseInfo.put("SText_caseName", resultList.get(0).get("courseName"));
//                    // 推荐结果
//                    courseInfo.put("ShortText_marketing", resultList.get(0).get("tjjg"));
//                    // 审批状态
//                    courseInfo.put("ShortText_approvalStatus", resultList.get(0).get("currentAuditstate"));
//                    // 部门
//                    courseInfo.put("ShortText_departLevelTwo", resultList.get(0).get("xmb"));
//                    // 单位
//                    courseInfo.put("ShortText_unit", resultList.get(0).get("szdw"));
//                    // 课程/案例类别
//                    courseInfo.put("ShortText_SText_caseType", resultList.get(0).get("category"));
//                    // 课时
//                    courseInfo.put("ShortText_spendTime", resultList.get(0).get("classHour"));
//                    // 培训对象
//                    courseInfo.put("ShortText_caseTarget", resultList.get(0).get("cultivateObj"));
//                    // 参与人
//                    courseInfo.put("StaffMulti_CYR", resultList.get(0).get("tdcy"));
//                    // 基层评审得分
//                    courseInfo.put("ShortText_basicScore", resultList.get(0).get("jcpsdf"));
//                    // 推荐结果
//                    courseInfo.put("ShortText_basicMarketing", resultList.get(0).get("tjjg"));
//                    // 审批结果
//                    courseInfo.put("ShortText_approvalResult", resultList.get(0).get("shjg"));
//
//                    courseInfo.put("rowStatus", "Added");
//                    courseList.add(courseInfo);
//                    dqHdmc.put("SheetInfo", courseList);
//                    fMap.put(hdmcId, dqHdmc);
//                }
//            }
//
//            Map<String, Object> paramMap = new HashMap<>();
//            // 课程申报选择
//            paramMap.put("RelevanceFormKCSB", splitID[j]);
//            // 课程评审ID
//            paramMap.put("ShortTextKCPSID", splitID[j]);
//            // 当前审批人
//            paramMap.put("ShortTextDQSPR", userName);
//
//            // 当前节点
//            paramMap.put("ShortTextDQJD", dBdqyw);
//            // 下一节点
//            paramMap.put("ShortTextXYJD", dBxyjd);
//
//            // 审核时间
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            paramMap.put("DateSHSJ", format.format(new Date()));
//            BizObjectCreatedModel checkInfo = new BizObjectCreatedModel("shrz", paramMap, false);
//            checkInfo.setSequenceStatus(SequenceStatus.COMPLETED.name());
//            String checkInfoId = getBizObjectFacade().saveBizObject(userId, checkInfo, false);
//            log.info("\n=======审核日志表单保存成功,bizObjectId={}",checkInfoId);
//            StringBuilder updateDQYWsql = new StringBuilder();
//            updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortTextDQYW = '" + subDqyw + "' WHERE T.id = '" + splitID[j] + "'");
//            int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
//            log.info("\n=======更新业务状态成功,updateNum={}",updateNum);
//        }
//        for (Map.Entry<String, Map<String, Object>> entry : fMap.entrySet()) {
//            Map<String, Object> map = entry.getValue();
//            // 发起基层领导审批流程
//            BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("DepartmentLeaderApproval", map, false);
//            String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
//            String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "deptManagerApproveFlow", bizObjectId, true);
//            log.info("\n=======基层领导审批流程发起成功,instanceId={}",instanceId);
//        }
        return getOkResponseResult(ywlx, "success");
    }

    private Map<String, String> nextStep(String id, boolean isFallback, String ywlx, int changeNum) {

        Map<String, String> step = new HashMap<>();

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");

        String nextStep = "";

        String dqyw = "";

        if (ywlx.equals("Undefined")) {
            // 从数据获取业务路线
            StringBuilder selectCourseInfoSql = new StringBuilder();
            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + id + "'");
            // 根据ID取得课程申报信息
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            ywlx = (String) resultList.get(0).get("ShortTextYWLX");
            dqyw = (String) resultList.get(0).get("ShortTextDQYW");
        }

        String[] split = ywlx.split(";");

        // 赋值下一节点
        if (StringUtils.isEmpty(dqyw)) {
            nextStep = split[0];
        } else {
            for (int i = 0; i < split.length; i++) {
                if (dqyw.equals(split[i])) {
                    if (isFallback) {
                        if (changeNum != 0) {
                            int j = i - changeNum;
                            nextStep = j > 0 ? split[j - 1] : "";
                        } else {
                            nextStep = i > 0 ? split[i - 1] : "";
                        }
                    } else {
                        if (changeNum != 0) {
                            int j = i + changeNum;
                            nextStep = j < split.length - 1 ? split[j + 1] : "";
                        } else {
                            nextStep = i < split.length - 1 ? split[i + 1] : "";
                        }
                    }
                    break;
                }
            }
        }
        step.put("nextStep", nextStep);
        step.put("dqyw", dqyw);
        return step;
    }

    private void logAdd(String stepNow, String stepNext, String courseId, String userName, String userId, boolean isStart) {

        String stepBasicStart = "基层信息审核";

        String stepCenterStart = "中心审核";

        String stepBasicEnd = "基层领导审批";

        String stepCenterEnd = "试讲结果确认与发布";

        Map<String, Object> paramMap = new HashMap<>();
        // 课程申报选择
        paramMap.put("RelevanceFormKCSB", courseId);
        // 课程评审ID
        paramMap.put("ShortTextKCPSID", courseId);
        // 当前审批人
        paramMap.put("ShortTextDQSPR", userName);

        // 当前节点
        paramMap.put("ShortTextDQJD", stepNow);

        if (StringUtils.isNotEmpty(stepNext)) {
            // 下一节点
            paramMap.put("ShortTextXYJD", stepNext);
        } else {
            if (stepBasicStart.equals(stepNow)) {
                stepNext = "发起基层信息审核";
            } else if (stepCenterStart.equals(stepNow)) {
                stepNext = "发起中心审核";
            } else if (stepBasicEnd.equals(stepNow)) {
                stepNext = "结束";
            } else if (stepCenterEnd.equals(stepNow)) {
                stepNext = "结束";
            } else {
                if (isStart) {
                    stepNext = "开始";
                } else {
                    stepNext = "结束";
                }
            }
            // 下一节点
            paramMap.put("ShortTextXYJD", stepNext);
        }

        // 审核时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("DateSHSJ", format.format(new Date()));
        BizObjectCreatedModel checkInfo = new BizObjectCreatedModel("shrz", paramMap, false);
        checkInfo.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String checkInfoId = getBizObjectFacade().saveBizObject(userId, checkInfo, false);
        log.info("\n=======审核日志表单保存成功,bizObjectId={}", checkInfoId);
    }

    private void sendRejectMessage(String courseId, String rejectPosition, String opinion) {

        String userId = getUserId();

        UserModel user = getOrganizationFacade().getUser(userId);

        String positionBasic = "基层信息审核";

        String positionCenter = "中心审核";

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        // 从数据获取业务路线
        StringBuilder selectCourseInfoSql = new StringBuilder();
        selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + courseId + "'");
        // 根据ID取得课程申报信息
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String courseName = MapUtils.getString(resultList.get(0), "courseName");
//        String kczkfr = MapUtils.getString(resultList.get(0), "kczkfr");

        StringBuilder searchLogSql = new StringBuilder();
        searchLogSql.append("SELECT * FROM `iwrwy_shrz` WHERE RelevanceFormKCSB = '" + courseId + "' ORDER BY createdTime DESC;");
        List<Map<String, Object>> logResult = entityManager.createNativeQuery(searchLogSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String creater = MapUtils.getString(logResult.get(0), "creater");
        String kczkfr = "[{\"id\":\"" + creater + "\",\"type\":3}]";

        String opinions;
        if (positionBasic.equals(rejectPosition)) {
            // 基层信息审核驳回
            opinions = MapUtils.getString(resultList.get(0), "shyj", opinion);
        } else if (positionCenter.equals(rejectPosition)) {
            // 中心审核驳回
            opinions = MapUtils.getString(resultList.get(0), "psyjZx");
        } else {
            // 未知位置驳回
            opinions = "未知位置驳回意见";
        }

        // 获取当前时间+1个月
        TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(timeZone);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        calendar.add(Calendar.MONTH, 1);
        String format = simpleDateFormat.format(calendar.getTime());

        BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel();
        bizObjectCreatedModel.setSchemaCode("ZCGL_TZTG");
        bizObjectCreatedModel.put("tzbt", "【课程申报】" + courseName + "-已被驳回");
        bizObjectCreatedModel.put("hhxr", kczkfr);
        bizObjectCreatedModel.put("tzrt", opinions);
        bizObjectCreatedModel.put("jzrq", format);
        String bizObject = getBizObjectFacade().saveBizObject(userId, bizObjectCreatedModel, false);
        log.info("\n=======驳回消息表单信息保存成功,instanceId={}", bizObject);
        String zcgl_tztg = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "ZCGL_TZTG", bizObject, true);
        log.info("\n=======驳回流程发起成功,instanceId={}", zcgl_tztg);
    }

    /**
     * 根据活动级别获取活动业务路线（取日志业务路线，推进日志，不更新业务节点）
     *
     * @param hdjb
     * @return
     */
    @GetMapping("/businessLineTwo")
    @Transactional
    public ResponseResult<String> businessLineTwo(@RequestParam(required = false) String hdjb, @RequestParam(required = false) String dqyw, @RequestParam String kcsbId, @RequestParam(required = false) String fallBack) {

        // 业务路线
        String ywlx = "Undefined";

        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);

        // 如果参数传入活动级别，则依据活动级别获取业务路线
        if (StringUtils.isNotEmpty(hdjb)) {
            String ywxlTableName = getBizObjectFacade().getTableName("ywxlNew");
            StringBuilder selectBusinessLineSql = new StringBuilder();
            selectBusinessLineSql.append("SELECT T.ywlx FROM `" + ywxlTableName + "` T WHERE T.xlmc = '" + hdjb + "'");
            ywlx = (String) entityManager.createNativeQuery(selectBusinessLineSql.toString()).getSingleResult();
        }

        String[] splitID = kcsbId.split(";");
        boolean useParam = true;
        // 若业务路线未定义，则未传入活动级别，后续根据id查找业务路线
        if ("Undefined".equals(ywlx)) {
            useParam = false;
        }

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        String shrzTableName = getBizObjectFacade().getTableName("shrz");
        Map<String, Map<String, Object>> fMap = new HashMap<>();
        // 处理传入的id拼接数据
        for (int j = 0; j < splitID.length; j++) {
            String subDqyw = "";
            String subYwlx = "";
            StringBuilder selectCourseInfoSql = new StringBuilder();
            StringBuilder selectCourseLogSql = new StringBuilder();
            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
            selectCourseLogSql.append("SELECT * FROM `" + shrzTableName + "` T WHERE T.ShortTextKCPSID = '" + splitID[j] + "' ORDER BY T.createdTime DESC LIMIT 1");
            // 根据ID取得课程申报信息
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            // 根据ID取得课程日志最新数据的下一节点为当前节点
            List<Map<String, Object>> logResultList = entityManager.createNativeQuery(selectCourseLogSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (!useParam) {
                subYwlx = (String) resultList.get(0).get("ShortTextYWLX");
                subDqyw = (String) logResultList.get(0).get("ShortTextXYJD");
            } else {
                subYwlx = ywlx;
                subDqyw = dqyw;
            }
            String[] split = subYwlx.split(";");
            String xyjd = "";
            String dBdqyw = "";
            String dBxyjd = "";
            String userName = user.getName();
            if (StringUtils.isEmpty(subDqyw)) {
                subDqyw = split[0];
                if (split.length < 2) {
                    xyjd = "done";
                } else {
                    xyjd = split[1];
                }
            } else {
                for (int i = 0; i < split.length; i++) {
                    if (subDqyw.equals(split[i])) {
                        if (StringUtils.isNotEmpty(fallBack)) {
                            dBdqyw = subDqyw;
                            subDqyw = i > 0 ? split[i - 1] : "";
                            dBxyjd = subDqyw;
                            xyjd = split[i];
                        } else {
                            dBdqyw = subDqyw;
                            subDqyw = i < split.length - 1 ? split[i + 1] : "done";
                            dBxyjd = subDqyw;
                            xyjd = i < split.length - 2 ? split[i + 2] : "done";
                        }
                        break;
                    }
                }
                // 若当前节点为审批相关，则发起对应审批流程
                if (subDqyw.contains("审批")) {
                    // 活动ID
                    String sbhdId = (String) resultList.get(0).get("RelevanceFormSBHD");
                    StringBuilder getHdmcByIdSql = new StringBuilder();
                    String sbhdNewTableName = getBizObjectFacade().getTableName("sbhdNew");
                    getHdmcByIdSql.append("SELECT * FROM `" + sbhdNewTableName + "` T WHERE T.id = '" + sbhdId + "'");
                    List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                    String hdmcId = (String) hdmcList.get(0).get("id");
                    String hdmc = (String) hdmcList.get(0).get("hdmc");
                    // 获取发起活动的部门
                    DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
                    if (!fMap.containsKey(hdmcId)) {
                        // 新增活动单位
                        Map<String, Object> smap = new HashMap<>();
                        // 子表
                        smap.put("SheetInfo", new ArrayList<>());
                        // 活动名称_发起人一级部门
                        smap.put("SText_actvNameAndDeptLevOne", hdmc + "_" + dept.getName());
                        fMap.put(hdmcId, smap);
                    }
                    Map<String, Object> dqHdmc = fMap.get(hdmcId);
                    List courseList = (List) dqHdmc.get("SheetInfo");
                    Map<String, Object> courseInfo = new HashMap<>();
                    // 课程ID
                    courseInfo.put("ShortTextCourseID", resultList.get(0).get("id"));
                    // 工号
                    courseInfo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
                    // 姓名
                    courseInfo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
                    // 课程/案例名称
                    courseInfo.put("SText_caseName", resultList.get(0).get("courseName"));
                    // 推荐结果
                    courseInfo.put("ShortText_marketing", resultList.get(0).get("tjjg"));
                    // 审批状态
                    courseInfo.put("ShortText_approvalStatus", resultList.get(0).get("currentAuditstate"));
                    // 部门
                    courseInfo.put("ShortText_departLevelTwo", resultList.get(0).get("xmb"));
                    // 单位
                    courseInfo.put("ShortText_unit", resultList.get(0).get("szdw"));
                    // 课程/案例类别
                    courseInfo.put("ShortText_SText_caseType", resultList.get(0).get("category"));
                    // 课时
                    courseInfo.put("ShortText_spendTime", resultList.get(0).get("classHour"));
                    // 培训对象
                    courseInfo.put("ShortText_caseTarget", resultList.get(0).get("cultivateObj"));
                    // 参与人
                    courseInfo.put("StaffMulti_CYR", resultList.get(0).get("tdcy"));
                    // 基层评审得分
                    courseInfo.put("ShortText_basicScore", resultList.get(0).get("jcpsdf"));
                    // 推荐结果
                    courseInfo.put("ShortText_basicMarketing", resultList.get(0).get("tjjg"));
                    // 审批结果
                    courseInfo.put("ShortText_approvalResult", resultList.get(0).get("shjg"));

                    courseInfo.put("rowStatus", "Added");
                    courseList.add(courseInfo);
                    dqHdmc.put("SheetInfo", courseList);
                    dqHdmc.put("ShortText_courseId", splitID[j]);
                    fMap.put(hdmcId, dqHdmc);
                }
            }

            Map<String, Object> paramMap = new HashMap<>();
            // 课程申报选择
            paramMap.put("RelevanceFormKCSB", splitID[j]);
            // 课程评审ID
            paramMap.put("ShortTextKCPSID", splitID[j]);
            // 当前审批人
            paramMap.put("ShortTextDQSPR", userName);

            // 当前节点
//            paramMap.put("ShortTextDQJD", dBdqyw);
            paramMap.put("ShortTextDQJD", "基层信息审核");
            // 下一节点
//            paramMap.put("ShortTextXYJD", dBxyjd);
            paramMap.put("ShortTextXYJD", "基层评审推荐");

            // 审核时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("DateSHSJ", format.format(new Date()));
            BizObjectCreatedModel checkInfo = new BizObjectCreatedModel("shrz", paramMap, false);
            checkInfo.setSequenceStatus(SequenceStatus.COMPLETED.name());
            String checkInfoId = getBizObjectFacade().saveBizObject(userId, checkInfo, false);
            log.info("\n=======审核日志表单保存成功,bizObjectId={}", checkInfoId);
            StringBuilder updateDQYWsql = new StringBuilder();
            updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortTextDQYW = '" + subDqyw + "' WHERE T.id = '" + splitID[j] + "'");
//            int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
//            log.info("\n=======更新业务状态成功,updateNum={}",updateNum);
        }
        for (Map.Entry<String, Map<String, Object>> entry : fMap.entrySet()) {
            Map<String, Object> map = entry.getValue();
            // 发起基层领导审批流程
            BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("DepartmentLeaderApproval", map, false);
            String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
            String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "deptManagerApproveFlow", bizObjectId, true);
            log.info("\n=======基层领导审批流程发起成功,instanceId={}", instanceId);
        }
        return getOkResponseResult(ywlx, "success");
    }

    /**
     * 根据活动级别获取活动业务路线（取日志当前节点，推进日志节点，更新业务节点）
     *
     * @param hdjb
     * @return
     */
    @GetMapping("/businessLineThree")
    @Transactional
    public ResponseResult<String> businessLineThree(@RequestParam(required = false) String hdjb, @RequestParam(required = false) String dqyw, @RequestParam String kcsbId, @RequestParam(required = false) String fallBack) {

        // 业务路线
        String ywlx = "Undefined";

        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);

        // 如果参数传入活动级别，则依据活动级别获取业务路线
        if (StringUtils.isNotEmpty(hdjb)) {
            String ywxlTableName = getBizObjectFacade().getTableName("ywxlNew");
            StringBuilder selectBusinessLineSql = new StringBuilder();
            selectBusinessLineSql.append("SELECT T.ywlx FROM `" + ywxlTableName + "` T WHERE T.xlmc = '" + hdjb + "'");
            ywlx = (String) entityManager.createNativeQuery(selectBusinessLineSql.toString()).getSingleResult();
        }

        String[] splitID = kcsbId.split(";");
        boolean useParam = true;
        // 若业务路线未定义，则未传入活动级别，后续根据id查找业务路线
        if ("Undefined".equals(ywlx)) {
            useParam = false;
        }

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        String shrzTableName = getBizObjectFacade().getTableName("shrz");
        Map<String, Map<String, Object>> fMap = new HashMap<>();
        // 处理传入的id拼接数据
        for (int j = 0; j < splitID.length; j++) {
            String subDqyw = "";
            String subYwlx = "";
            StringBuilder selectCourseInfoSql = new StringBuilder();
            StringBuilder selectCourseLogSql = new StringBuilder();
            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
            selectCourseLogSql.append("SELECT * FROM `" + shrzTableName + "` T WHERE T.ShortTextKCPSID = '" + splitID[j] + "' ORDER BY T.createdTime DESC LIMIT 1");
            // 根据ID取得课程申报信息
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            // 根据ID取得课程日志最新数据的下一节点为当前节点
            List<Map<String, Object>> logResultList = entityManager.createNativeQuery(selectCourseLogSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (!useParam) {
                subYwlx = (String) resultList.get(0).get("ShortTextYWLX");
                subDqyw = (String) logResultList.get(0).get("ShortTextXYJD");
            } else {
                subYwlx = ywlx;
                subDqyw = dqyw;
            }
            String[] split = subYwlx.split(";");
            String xyjd = "";
            String dBdqyw = "";
            String dBxyjd = "";
            String userName = user.getName();
            if (StringUtils.isEmpty(subDqyw)) {
                subDqyw = split[0];
                if (split.length < 2) {
                    xyjd = "done";
                } else {
                    xyjd = split[1];
                }
            } else {
                for (int i = 0; i < split.length; i++) {
                    if (subDqyw.equals(split[i])) {
                        if (StringUtils.isNotEmpty(fallBack)) {
                            dBdqyw = subDqyw;
                            subDqyw = i > 0 ? split[i - 1] : "";
                            dBxyjd = subDqyw;
                            xyjd = split[i];
                        } else {
                            dBdqyw = subDqyw;
                            subDqyw = i < split.length - 1 ? split[i + 1] : "done";
                            dBxyjd = subDqyw;
                            xyjd = i < split.length - 2 ? split[i + 2] : "done";
                        }
                        break;
                    }
                }
                // 若当前节点为审批相关，则发起对应审批流程
                if (subDqyw.contains("审批")) {
                    // 活动ID
                    String sbhdId = (String) resultList.get(0).get("RelevanceFormSBHD");
                    StringBuilder getHdmcByIdSql = new StringBuilder();
                    String sbhdNewTableName = getBizObjectFacade().getTableName("sbhdNew");
                    getHdmcByIdSql.append("SELECT * FROM `" + sbhdNewTableName + "` T WHERE T.id = '" + sbhdId + "'");
                    List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                    String hdmcId = (String) hdmcList.get(0).get("id");
                    String hdmc = (String) hdmcList.get(0).get("hdmc");
                    // 获取发起活动的部门
                    DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
                    if (!fMap.containsKey(hdmcId)) {
                        // 新增活动单位
                        Map<String, Object> smap = new HashMap<>();
                        // 子表
                        smap.put("SheetInfo", new ArrayList<>());
                        // 活动名称_发起人一级部门
                        smap.put("SText_actvNameAndDeptLevOne", hdmc + "_" + dept.getName());
                        fMap.put(hdmcId, smap);
                    }
                    Map<String, Object> dqHdmc = fMap.get(hdmcId);
                    List courseList = (List) dqHdmc.get("SheetInfo");
                    Map<String, Object> courseInfo = new HashMap<>();
                    // 课程ID
                    courseInfo.put("ShortTextCourseID", resultList.get(0).get("id"));
                    // 工号
                    courseInfo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
                    // 姓名
                    courseInfo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
                    // 课程/案例名称
                    courseInfo.put("SText_caseName", resultList.get(0).get("courseName"));
                    // 推荐结果
                    courseInfo.put("ShortText_marketing", resultList.get(0).get("tjjg"));
                    // 审批状态
                    courseInfo.put("ShortText_approvalStatus", resultList.get(0).get("currentAuditstate"));
                    // 部门
                    courseInfo.put("ShortText_departLevelTwo", resultList.get(0).get("xmb"));
                    // 单位
                    courseInfo.put("ShortText_unit", resultList.get(0).get("szdw"));
                    // 课程/案例类别
                    courseInfo.put("ShortText_SText_caseType", resultList.get(0).get("category"));
                    // 课时
                    courseInfo.put("ShortText_spendTime", resultList.get(0).get("classHour"));
                    // 培训对象
                    courseInfo.put("ShortText_caseTarget", resultList.get(0).get("cultivateObj"));
                    // 参与人
                    courseInfo.put("StaffMulti_CYR", resultList.get(0).get("tdcy"));
                    // 基层评审得分
                    courseInfo.put("ShortText_basicScore", resultList.get(0).get("jcpsdf"));
                    // 推荐结果
                    courseInfo.put("ShortText_basicMarketing", resultList.get(0).get("tjjg"));
                    // 审批结果
                    courseInfo.put("ShortText_approvalResult", resultList.get(0).get("shjg"));

                    courseInfo.put("rowStatus", "Added");
                    courseList.add(courseInfo);
                    dqHdmc.put("SheetInfo", courseList);
                    fMap.put(hdmcId, dqHdmc);
                }
            }

            Map<String, Object> paramMap = new HashMap<>();
            // 课程申报选择
            paramMap.put("RelevanceFormKCSB", splitID[j]);
            // 课程评审ID
            paramMap.put("ShortTextKCPSID", splitID[j]);
            // 当前审批人
            paramMap.put("ShortTextDQSPR", userName);

            // 当前节点
            paramMap.put("ShortTextDQJD", dBdqyw);
            // 下一节点
            paramMap.put("ShortTextXYJD", dBxyjd);

            // 审核时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("DateSHSJ", format.format(new Date()));
            BizObjectCreatedModel checkInfo = new BizObjectCreatedModel("shrz", paramMap, false);
            checkInfo.setSequenceStatus(SequenceStatus.COMPLETED.name());
            String checkInfoId = getBizObjectFacade().saveBizObject(userId, checkInfo, false);
            log.info("\n=======审核日志表单保存成功,bizObjectId={}", checkInfoId);
            StringBuilder updateDQYWsql = new StringBuilder();
            updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortTextDQYW = '" + subDqyw + "' WHERE T.id = '" + splitID[j] + "'");
            int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
            log.info("\n=======更新业务状态成功,updateNum={}", updateNum);
        }
        for (Map.Entry<String, Map<String, Object>> entry : fMap.entrySet()) {
            Map<String, Object> map = entry.getValue();
            // 发起基层领导审批流程
            BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("DepartmentLeaderApproval", map, false);
            String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
            String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "deptManagerApproveFlow", bizObjectId, true);
            log.info("\n=======基层领导审批流程发起成功,instanceId={}", instanceId);
        }
        return getOkResponseResult(ywlx, "success");
    }

    /**
     * 发起申报check
     *
     * @param activeId
     * @return
     */
    @GetMapping("launchDeclareCheck")
    public ResponseResult<courseInfoVo> launchDeclareCheck(@RequestParam String activeId) {

        String userId = getUserId();
        courseInfoVo courseInfoVo = new courseInfoVo();
        courseInfoVo.setExist(false);
        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        StringBuilder getInfoByIdSql = new StringBuilder();
        getInfoByIdSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.RelevanceFormSBHD = '" + activeId + "' AND T.creater = '" + userId + "';");
        List<Map<String, Object>> infolist = entityManager.createNativeQuery(getInfoByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(infolist)) {
            courseInfoVo.setExist(false);
            // 初次申请
            return getOkResponseResult(courseInfoVo, "success");
        } else {
            // 基层级审核结果
            String shjg = MapUtils.getString(infolist.get(0), "shjg");
            // 中心级审核结果
            String shjgZx = MapUtils.getString(infolist.get(0), "shjgZx");
            // 活动级别
            String hdjb = MapUtils.getString(infolist.get(0), "hdjb");
            if ("驳回修改".equals(shjg)) {
                courseInfoVo.setBack(true);
            } else {
                courseInfoVo.setBack(false);
            }

            if ("中心级评审".equals(hdjb) && "驳回修改".equals(shjgZx)) {
                courseInfoVo.setBack(true);
            }

            courseInfoVo.setDataId(MapUtils.getString(infolist.get(0), "id"));
            courseInfoVo.setSequenceStatus(MapUtils.getString(infolist.get(0), "sequenceStatus"));
            courseInfoVo.setExist(true);
            // 重复申请
            return getOkResponseResult(courseInfoVo, "success");
        }
    }

    /**
     * 评聘发起申报check
     *
     * @param activeId
     * @return
     */
    @GetMapping("launchDeclareCheckForTeacher")
    public ResponseResult<courseInfoVo> launchDeclareCheckForTeacher(@RequestParam String activeId) {

        String userId = getUserId();
        courseInfoVo courseInfoVo = new courseInfoVo();
        courseInfoVo.setExist(false);
        String jssbTableName = getBizObjectFacade().getTableName("jssb");
        StringBuilder getInfoByIdSql = new StringBuilder();
//        getInfoByIdSql.append("SELECT * FROM `" + jssbTableName + "` T WHERE T.hdmc = '" + activeId + "' AND T.creater = '" + userId + "' and T.zt != '已提交';");
        getInfoByIdSql.append("SELECT * FROM `" + jssbTableName + "` T WHERE T.hdmc = '" + activeId + "' AND T.creater = '" + userId + "';");
        List<Map<String, Object>> infolist = entityManager.createNativeQuery(getInfoByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(infolist)) {
            courseInfoVo.setExist(false);
            // 初次申请
            return getOkResponseResult(courseInfoVo, "success");
        } else {
            courseInfoVo.setDataId(MapUtils.getString(infolist.get(0), "id"));
            courseInfoVo.setSequenceStatus(MapUtils.getString(infolist.get(0), "sequenceStatus"));
            courseInfoVo.setExist(true);
            // 重复申请
            return getOkResponseResult(courseInfoVo, "success");
        }
    }

//    /**
//     * 课程更新管理提交，数据复制逻辑接口
//     *
//     * @param kcsbId
//     * @return
//     */
//    @GetMapping("courseUpdateMsgToTeacher")
//    public ResponseResult<String> courseUpdateMsgToTeacher(@RequestParam String kcsbId) {
//
//        String[] splitID = kcsbId.split(";");
//
//        // 获取课程更新活动表名
//        String courseUpdateTableName = getBizObjectFacade().getTableName("courseUpdate");
//        // 获取课程更新活动子表通知更新课程清单表名
//        String SheetTZGXKCQDTableName = getBizObjectFacade().getTableName("SheetTZGXKCQD");
//        // 获取入库课程清单信息
//        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
//        // 获取当前操作人id
//        String userId = getUserId();
//
//        for (int j = 0; j < splitID.length; j++) {
//            StringBuilder selectCourseUpdateInfoSql = new StringBuilder();
//            selectCourseUpdateInfoSql.append("SELECT * FROM `" + courseUpdateTableName + "` T WHERE T.id = '" + splitID[j] + "'");
//            // 根据ID取得课程更新活动信息
//            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseUpdateInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            if (CollectionUtils.isEmpty(resultList)) {
//                continue;
//            }
//            String id = (String) resultList.get(0).get("id");
//            StringBuilder selectSubTSql = new StringBuilder();
//            selectSubTSql.append("SELECT * FROM `" + SheetTZGXKCQDTableName + "` T WHERE T.parentId = '" + id + "'");
//            // 根据ID取得课程更新活动子表，待更新课程信息
//            List<Map<String, Object>> updateCoursesList = entityManager.createNativeQuery(selectSubTSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            // 更新课程编号统计
//            List<String> courseCode = new ArrayList<>();
//            for (Map<String, Object> stringObjectMap : updateCoursesList) {
//                // 获取课程编码
//                String shortText_kcbm = (String) stringObjectMap.get("ShortText_KCBM");
//                courseCode.add(shortText_kcbm);
//            }
//            List<Map<String, Object>> maps = courseUpdateRepository.kcqdUpdateList(courseCode);
//
//            // 获取入库课程清单子表表名
//            String kcqdCourseStructuresTabName = getBizObjectFacade().getTableName("kcqdCourseStructures");
//            String kcqdJudgmentQuestionTabName = getBizObjectFacade().getTableName("kcqdJudgmentQuestion");
//            String kcqdChoiceQuestionTabName = getBizObjectFacade().getTableName("kcqdChoiceQuestion");
//            String Sheet_kcqd_psdfTabName = getBizObjectFacade().getTableName("Sheet_kcqd_psdf");
//            //
//            courseTransfer(userId, resultList, maps, true, kcqdCourseStructuresTabName, kcqdJudgmentQuestionTabName, kcqdChoiceQuestionTabName, Sheet_kcqd_psdfTabName,
//                    "courseStructureskcgxfk", "judgmentQuestionkcgxfk", "choiceQuestionkcgxfk", "psdfbkcgxfk",
//                    "kcgxfk");
//        }
//        return getOkResponseResult("success", "success");
//    }

    @PostMapping("checkCourseInUpdate")
    public ResponseResult checkCourseInUpdate(@RequestBody List<String> activeIdList) {

        // 获取课程更新活动表名
        String courseUpdateTableName = getBizObjectFacade().getTableName("courseUpdate");
        // 获取课程更新活动子表通知更新课程清单表名
        String SheetTZGXKCQDTableName = getBizObjectFacade().getTableName("SheetTZGXKCQD");
        // 获取入库课程清单信息
        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
        // 更新课程编号统计
        List<String> bizIdList = new ArrayList<>();
        // 课程对应活动名称
        Map<String, CourseUpdateInfo> matchGxhdmc = new HashMap<>();
        for (String id : activeIdList) {
            StringBuilder selectCourseUpdateInfoSql = new StringBuilder();
            selectCourseUpdateInfoSql.append("SELECT * FROM `" + courseUpdateTableName + "` T WHERE T.id = '" + id + "'");
            // 根据ID取得课程更新活动信息
            List<Map<String, Object>> resultCourseUpdateList = entityManager.createNativeQuery(selectCourseUpdateInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            String gxhdmc = (String) resultCourseUpdateList.get(0).get("gxhdmc");
            Date toTime = (Date) resultCourseUpdateList.get(0).get("toTime");
            CourseUpdateInfo courseUpdateInfo = new CourseUpdateInfo();
            courseUpdateInfo.setId(id);
            courseUpdateInfo.setGxhdmc(gxhdmc);
            courseUpdateInfo.setToTime(toTime);

            StringBuilder selectSubTSql = new StringBuilder();
            selectSubTSql.append("SELECT * FROM `" + SheetTZGXKCQDTableName + "` T WHERE T.parentId = '" + id + "'");
            // 根据ID取得课程更新活动子表，待更新课程信息
            List<Map<String, Object>> updateCoursesList = entityManager.createNativeQuery(selectSubTSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();

            for (Map<String, Object> stringObjectMap : updateCoursesList) {
                // 获取课程编码
                String kcbh = (String) stringObjectMap.get("ShortText_KCBM");
                StringBuilder selectKcqdSql = new StringBuilder();
                selectKcqdSql.append("SELECT * FROM `" + kcqdTableName + "` WHERE kcbh = '" + kcbh + "'");
                List<Map<String, Object>> kcqd = entityManager.createNativeQuery(selectKcqdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                String dataId = (String) kcqd.get(0).get("id");
                bizIdList.add(dataId);
                matchGxhdmc.put(dataId, courseUpdateInfo);
            }
        }

        if (CollectionUtils.isEmpty(bizIdList)) {
            return getErrResponseResult(-1L, "参数不能为空");
        }

        List<String> failList = new ArrayList<>();

        bizIdList.forEach(bizId -> {
            try {
                ResponseResult responseResult = checkCourseInUpdate(bizId, matchGxhdmc);
                if (responseResult.getErrcode() != 0) {
                    failList.add(responseResult.getErrmsg());
                }
            } catch (RuntimeException e) {

                failList.add(e.getMessage());
            } catch (Exception e) {
                failList.add(StrUtil.format("系统处理异常:{}", bizId));
            }
        });

        if (CollectionUtils.isEmpty(failList)) {
            return getOkResponseResult("检查全部通过");
        } else if (bizIdList.size() == failList.size()) {
            return getErrResponseResult(-1L, StrUtil.format("检查全部失败:{}", JSON.toJSONString(failList)));
        } else {
            return getErrResponseResult(-1L, StrUtil.format("检查部分失败:{}", JSON.toJSONString(failList)));
        }
    }

    private ResponseResult checkCourseInUpdate(String bizId, Map<String, CourseUpdateInfo> gxhdInfo) {

        log.info("\n===========进入检测课程是否在更新中方法,bizId={}", bizId);
        ResponseResult.ResponseResultBuilder<Object> resp = ResponseResult.builder().errcode(-1l);

        //获取入库课程清单数据
        BizObjectCreatedModel kcqd = getBizObjectFacade().getBizObject("kcqd", bizId);

        if (kcqd == null) {
            return resp.errmsg("入库课程清单数据不存在").build();
        }

        String kcbh = kcqd.getString("kcbh");
        if (org.apache.commons.lang.StringUtils.isEmpty(kcbh)) {
            return resp.errmsg(StrUtil.format("课程编号不能为空:课程Id={}", bizId)).build();
        }

        //判断课程更新数据是否存在
        BizObjectQueryModel query = new BizObjectQueryModel();
        query.setSchemaCode("kcgxfk");
        query.setQueryCode("kcsb");
        query.setPageable(new PageableImpl(0, 10));
        List<FilterExpression> itList = new ArrayList<>();
        FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
        itList.add(it);
        it = Q.it("gxfk", FilterExpression.Op.Eq, "更新");
        itList.add(it);
        it = Q.it("fbzt", FilterExpression.Op.NotEq, "已发布");
        itList.add(it);
        it = Q.it("cancel", FilterExpression.Op.Eq, "启用");
        itList.add(it);
        FilterExpression.And and = Q.and(itList);
        query.setFilterExpr(and);
        Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(query);

        BizObjectQueryModel query2 = new BizObjectQueryModel();
        query2.setSchemaCode("kcgxfk");
        query2.setQueryCode("kcsb");
        query2.setPageable(new PageableImpl(0, 10));
        List<FilterExpression> itList2 = new ArrayList<>();
        FilterExpression.Item it2 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
        itList2.add(it2);
        it2 = Q.it("gxfk", FilterExpression.Op.Eq, "未反馈");
        itList2.add(it2);
        it2 = Q.it("cancel", FilterExpression.Op.Eq, "启用");
        itList2.add(it2);
        FilterExpression.And and2 = Q.and(itList2);
        query2.setFilterExpr(and2);
        Page<BizObjectModel> page2 = bizObjectFacade.queryBizObjects(query2);

        BizObjectQueryModel query3 = new BizObjectQueryModel();
        query3.setSchemaCode("kcgxfk");
        query3.setQueryCode("kcsb");
        query3.setPageable(new PageableImpl(0, 10));
        List<FilterExpression> itList3 = new ArrayList<>();
        FilterExpression.Item it3 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
        itList3.add(it3);
        it3 = Q.it("gxfk", FilterExpression.Op.IsNull, null);
        itList3.add(it3);
        it3 = Q.it("cancel", FilterExpression.Op.Eq, "启用");
        itList3.add(it3);
        FilterExpression.And and3 = Q.and(itList3);
        query3.setFilterExpr(and3);
        Page<BizObjectModel> page3 = bizObjectFacade.queryBizObjects(query3);

        if (page.getTotal() > 0 || page.getContent().size() > 0 || page2.getTotal() > 0 || page2.getContent().size() > 0 || page3.getTotal() > 0 || page3.getContent().size() > 0) {
            return resp.errmsg(StrUtil.format("课程更新未反馈或已在更新中,课程编号:{}", kcbh)).build();
        }

        return resp.errcode(0L).errmsg("课程更新检查通过").build();

    }

    /**
     * 启动课程更新
     *
     * @param activeIdList
     * @return
     */
    @PostMapping("courseUpdateMsgToTeacher")
    public ResponseResult courseUpdateMsgToTeacher(@RequestBody List<String> activeIdList) {

        // 获取课程更新活动表名
        String courseUpdateTableName = getBizObjectFacade().getTableName("courseUpdate");
        // 获取课程更新活动子表通知更新课程清单表名
        String SheetTZGXKCQDTableName = getBizObjectFacade().getTableName("SheetTZGXKCQD");
        // 获取入库课程清单信息
        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
        // 更新课程编号统计
        List<String> bizIdList = new ArrayList<>();
        // 课程对应活动名称
        Map<String, CourseUpdateInfo> matchGxhdmc = new HashMap<>();
        for (String id : activeIdList) {
            StringBuilder selectCourseUpdateInfoSql = new StringBuilder();
            selectCourseUpdateInfoSql.append("SELECT * FROM `" + courseUpdateTableName + "` T WHERE T.id = '" + id + "'");
            // 根据ID取得课程更新活动信息
            List<Map<String, Object>> resultCourseUpdateList = entityManager.createNativeQuery(selectCourseUpdateInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            String gxhdmc = (String) resultCourseUpdateList.get(0).get("gxhdmc");
            Date toTime = (Date) resultCourseUpdateList.get(0).get("toTime");
            CourseUpdateInfo courseUpdateInfo = new CourseUpdateInfo();
            courseUpdateInfo.setId(id);
            courseUpdateInfo.setGxhdmc(gxhdmc);
            courseUpdateInfo.setToTime(toTime);

            StringBuilder selectSubTSql = new StringBuilder();
            selectSubTSql.append("SELECT * FROM `" + SheetTZGXKCQDTableName + "` T WHERE T.parentId = '" + id + "'");
            // 根据ID取得课程更新活动子表，待更新课程信息
            List<Map<String, Object>> updateCoursesList = entityManager.createNativeQuery(selectSubTSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();

            for (Map<String, Object> stringObjectMap : updateCoursesList) {
                // 获取课程编码
                String kcbh = (String) stringObjectMap.get("ShortText_KCBM");
                StringBuilder selectKcqdSql = new StringBuilder();
                selectKcqdSql.append("SELECT * FROM `" + kcqdTableName + "` WHERE kcbh = '" + kcbh + "'");
                List<Map<String, Object>> kcqd = entityManager.createNativeQuery(selectKcqdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                String dataId = (String) kcqd.get(0).get("id");
                bizIdList.add(dataId);
                matchGxhdmc.put(dataId, courseUpdateInfo);
            }
        }

        if (CollectionUtils.isEmpty(bizIdList)) {
            return getErrResponseResult(-1L, "参数不能为空");
        }

        List<String> failList = new ArrayList<>();

        bizIdList.forEach(bizId -> {
            try {
                ResponseResult responseResult = courseUpdate(bizId, matchGxhdmc);
                if (responseResult.getErrcode() != 0) {
                    failList.add(responseResult.getErrmsg());
                }
            } catch (RuntimeException e) {

                failList.add(e.getMessage());
            } catch (Exception e) {
                failList.add(StrUtil.format("系统处理异常:{}", bizId));
            }
        });

        if (CollectionUtils.isEmpty(failList)) {
            return getOkResponseResult("全部成功");
        } else if (bizIdList.size() == failList.size()) {
            return getErrResponseResult(-1L, StrUtil.format("启动全部失败:{}", JSON.toJSONString(failList)));
        } else {
            return getErrResponseResult(-1L, StrUtil.format("启动部分失败:{}", JSON.toJSONString(failList)));
        }
    }

    private ResponseResult courseUpdate(String bizId, Map<String, CourseUpdateInfo> gxhdInfo) {

        log.info("\n===========进入启动课程更新方法,bizId={}", bizId);
        ResponseResult.ResponseResultBuilder<Object> resp = ResponseResult.builder().errcode(-1l);

        //获取入库课程清单数据
        BizObjectCreatedModel kcqd = getBizObjectFacade().getBizObject("kcqd", bizId);

        if (kcqd == null) {
            return resp.errmsg("入库课程清单数据不存在").build();
        }

        String kcbh = kcqd.getString("kcbh");
        if (org.apache.commons.lang.StringUtils.isEmpty(kcbh)) {
            return resp.errmsg(StrUtil.format("课程编号不能为空:课程Id={}", bizId)).build();
        }

        //判断课程更新数据是否存在
        BizObjectQueryModel query = new BizObjectQueryModel();
        query.setSchemaCode("kcgxfk");
        query.setQueryCode("kcsb");
        query.setPageable(new PageableImpl(0, 10));
        List<FilterExpression> itList = new ArrayList<>();
        FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
        itList.add(it);
        it = Q.it("gxfk", FilterExpression.Op.Eq, "更新");
        itList.add(it);
        it = Q.it("fbzt", FilterExpression.Op.NotEq, "已发布");
        itList.add(it);
        it = Q.it("cancel", FilterExpression.Op.Eq, "启用");
        itList.add(it);
        FilterExpression.And and = Q.and(itList);
        query.setFilterExpr(and);
        Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(query);

        BizObjectQueryModel query2 = new BizObjectQueryModel();
        query2.setSchemaCode("kcgxfk");
        query2.setQueryCode("kcsb");
        query2.setPageable(new PageableImpl(0, 10));
        List<FilterExpression> itList2 = new ArrayList<>();
        FilterExpression.Item it2 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
        itList2.add(it2);
        it2 = Q.it("gxfk", FilterExpression.Op.Eq, "未反馈");
        itList2.add(it2);
        it2 = Q.it("cancel", FilterExpression.Op.Eq, "启用");
        itList2.add(it2);
        FilterExpression.And and2 = Q.and(itList2);
        query2.setFilterExpr(and2);
        Page<BizObjectModel> page2 = bizObjectFacade.queryBizObjects(query2);

        BizObjectQueryModel query3 = new BizObjectQueryModel();
        query3.setSchemaCode("kcgxfk");
        query3.setQueryCode("kcsb");
        query3.setPageable(new PageableImpl(0, 10));
        List<FilterExpression> itList3 = new ArrayList<>();
        FilterExpression.Item it3 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
        itList3.add(it3);
        it3 = Q.it("gxfk", FilterExpression.Op.IsNull, null);
        itList3.add(it3);
        it3 = Q.it("cancel", FilterExpression.Op.Eq, "启用");
        itList3.add(it3);
        FilterExpression.And and3 = Q.and(itList3);
        query3.setFilterExpr(and3);
        Page<BizObjectModel> page3 = bizObjectFacade.queryBizObjects(query3);

        if (page.getTotal() > 0 || page.getContent().size() > 0 || page2.getTotal() > 0 || page2.getContent().size() > 0 || page3.getTotal() > 0 || page3.getContent().size() > 0) {
            return resp.errmsg(StrUtil.format("课程更新未反馈或已在更新中,课程编号:{}", kcbh)).build();
        }

        //组合课程更新反馈数据
        BizSchemaModel bizSchemaModel = this.getAppManagementFacade().getBizSchemaBySchemaCode("kcgxfk", true);

        //获取数据项code , 不是子表,已发布,不是默认字段
        List<String> fieldList = bizSchemaModel.getProperties().stream()
                .filter(prop -> !prop.getDefaultProperty() && prop.getPropertyType() != BizPropertyType.CHILD_TABLE && prop.getPublished())
                .map(BizPropertyModel::getCode).collect(Collectors.toList());

        //创建更新普通数据
        Map<String, Object> data = new HashMap<>();
        fieldList.forEach(f -> data.put(f, kcqd.get(f)));

        // 获取更新课程对应活动信息
        CourseUpdateInfo courseUpdateInfo = gxhdInfo.get(bizId);

        // 获取课程更新活动数据
        BizObjectCreatedModel courseUpdate = getBizObjectFacade().getBizObject("courseUpdate", courseUpdateInfo.getId());

        if (courseUpdate == null) {
            return resp.errmsg("课程更新管理数据不存在").build();
        }


//        data.put("sbr",kcqd.get("creater"));
//        data.put("sbsj",kcqd.getCreatedTime());
//        data.put("kczt","未启用");
//        // 点赞数
//        data.put("dzs",kcqd.get("dzs"));
//        // 学习人次
//        data.put("xxrc",0);
//        // 当日是否学习
//        data.put("drsfxr",false);
//        // 是否已点赞
//        data.put("sfydz",false);
//        // 年度
//        data.put("psnd",kcqd.get("year"));
//        // 课程分类/
//        data.put("hdlb",kcqd.get("modality"));
        // 开放范围
        data.put("DropdownArea", kcqd.get("previewArea"));
//        // 可开放范围
//        data.put("StaffDeptMix",kcqd.get("kkffw"));
        // 课程等级/评审级别
        data.put("kcdj", kcqd.get("psjb"));
        // 更新活动名称
        data.put("gxhdmc", courseUpdateInfo.getGxhdmc());
        // 更新活动截止时间
        data.put("gxjzrq", courseUpdateInfo.getToTime());
        // 更新活动附件
        data.put("fjxz", courseUpdate.get("AttachTZFJ"));
        // 更新活动备注
        data.put("bz", courseUpdate.get("dataInfo"));
        // 更新反馈
        data.put("gxfk", "未反馈");
        // 更新状态
        data.put("gxzt", "未反馈");
        // 设定更新课程数据默认状态为启用
        data.put("cancel", "启用");
        // 设定更新活动id
        data.put("activeId", courseUpdateInfo.getId());

        // 附件拷贝
        attachmentService.attachmentCopy(data, Lists.newArrayList("kcfm", "jssc", "sjfj", "ckzl", "fj"));


//        // 课程中开发人，文本赋值
//        SelectionValue kczkfr = kcqd.getSelectionObject("kczkfr");
//        if (kczkfr != null) {
//            data.put("kczkfrtxt",kczkfr.getName());
//        }


        //创建子表数据,课程结构kcqdCourseStructures,判断题kcqdJudgmentQuestion,选择题kcqdChoiceQuestion

        List<String> subDefaultCodeList = new ArrayList<>(Arrays.asList("id", "parentId", "modifier", "modifiedTime"));
        //课程结构 courseStructureskcgxfk
        List<Map<String, Object>> courseStructuresList = (List<Map<String, Object>>) kcqd.getObject("kcqdCourseStructures");
        if (CollectionUtils.isNotEmpty(courseStructuresList)) {

            courseStructuresList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("courseStructureskcgxfk", courseStructuresList);
        }

        //课程结构 kcqdalkcjgkcgxfk
        List<Map<String, Object>> kcqdalkcjgList = (List<Map<String, Object>>) kcqd.getObject("kcqdalkcjg");
        if (CollectionUtils.isNotEmpty(kcqdalkcjgList)) {

            kcqdalkcjgList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdalkcjgkcgxfk", kcqdalkcjgList);
        }


//        判断题 judgmentQuestionkcgxfk
        List<Map<String, Object>> judgmentQuestionList = (List<Map<String, Object>>) kcqd.getObject("kcqdJudgmentQuestion");
        if (CollectionUtils.isNotEmpty(judgmentQuestionList)) {

            judgmentQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("judgmentQuestionkcgxfk", judgmentQuestionList);
        }

//        选择题 choiceQuestionkcgxfk
        List<Map<String, Object>> choiceQuestionList = (List<Map<String, Object>>) kcqd.getObject("kcqdChoiceQuestion");
        if (CollectionUtils.isNotEmpty(choiceQuestionList)) {

            choiceQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("choiceQuestionkcgxfk", choiceQuestionList);
        }

        BizObjectCreatedModel bizModel = new BizObjectCreatedModel("kcgxfk", data, false);
        bizModel.setName(kcqd.getString("courseName"));
        bizModel.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String rkId = getBizObjectFacade().saveBizObject(getUserId(), bizModel, false);

        log.info("创建课程更新反馈表单数据成功,返回id={}", rkId);


//        if (rkId != null) {
//            //修改课程申报状态 已入库, 申报进度
//
//            Map<String, Object> sbjd = new HashMap<>();
//            sbjd.put("sbjdt",4);
//            sbjd.put("ShortTextDQYW","已入库");
//            BizObjectCreatedModel sbjdBiz  = new BizObjectCreatedModel("kcsbNew", sbjd, false);
//            sbjdBiz.setId(bizId);
//            getBizObjectFacade().saveBizObject(getUserId(),sbjdBiz,false);
//        }


        return resp.errcode(0L).errmsg("课程更新反馈成功").build();

    }

    /**
     * 发布更新结果
     *
     * @param selectedIdList
     * @return
     */
    @PostMapping("courseUpdateToSystem")
    public ResponseResult courseUpdateToSystem(@RequestBody List<String> selectedIdList) {

//        // 获取课程更新活动表名
//        String courseUpdateTableName = getBizObjectFacade().getTableName("courseUpdate");
//        // 获取课程更新活动子表通知更新课程清单表名
//        String SheetTZGXKCQDTableName = getBizObjectFacade().getTableName("SheetTZGXKCQD");
//        // 获取入库课程清单信息
//        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
//        // 更新课程编号统计
//        List<String> bizIdList = new ArrayList<>();
//        // 课程对应活动名称
//        Map<String, CourseUpdateInfo> matchGxhdmc = new HashMap<>();
//        for (String id : activeIdList) {
//            StringBuilder selectCourseUpdateInfoSql = new StringBuilder();
//            selectCourseUpdateInfoSql.append("SELECT * FROM `" + courseUpdateTableName + "` T WHERE T.id = '" + id + "'");
//            // 根据ID取得课程更新活动信息
//            List<Map<String, Object>> resultCourseUpdateList = entityManager.createNativeQuery(selectCourseUpdateInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            String gxhdmc = (String) resultCourseUpdateList.get(0).get("gxhdmc");
//            Date toTime = (Date) resultCourseUpdateList.get(0).get("toTime");
//            CourseUpdateInfo courseUpdateInfo = new CourseUpdateInfo();
//            courseUpdateInfo.setGxhdmc(gxhdmc);
//            courseUpdateInfo.setToTime(toTime);
//
//            StringBuilder selectSubTSql = new StringBuilder();
//            selectSubTSql.append("SELECT * FROM `" + SheetTZGXKCQDTableName + "` T WHERE T.parentId = '" + id + "'");
//            // 根据ID取得课程更新活动子表，待更新课程信息
//            List<Map<String, Object>> updateCoursesList = entityManager.createNativeQuery(selectSubTSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//
//            for (Map<String, Object> stringObjectMap : updateCoursesList) {
//                // 获取课程编码
//                String kcbh = (String) stringObjectMap.get("ShortText_KCBM");
//                StringBuilder selectKcqdSql = new StringBuilder();
//                selectKcqdSql.append("SELECT * FROM `" + kcqdTableName + "` WHERE kcbh = '" + kcbh + "'");
//                List<Map<String, Object>> kcqd = entityManager.createNativeQuery(selectKcqdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//                String dataId = (String) kcqd.get(0).get("id");
//                bizIdList.add(dataId);
//                matchGxhdmc.put(dataId, courseUpdateInfo);
//            }
//        }

        // 获取课程更新反馈表名
        String kcgxfkTableName = getBizObjectFacade().getTableName("kcgxfk");
        // 获取入库课程清单表明
        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");

        // 更新课程统计
        List<String> bizIdList = new ArrayList<>();
        // 入库课程清单id与课程更新反馈id匹配
        Map<String, String> matchKcqdId = new HashMap<>();
        // 入库课程清单id与课程更新反馈id匹配
        Map<String, String> matchKcgxfkId = new HashMap<>();

        if (CollectionUtils.isEmpty(selectedIdList)) {
            return getErrResponseResult(-1L, "参数不能为空");
        }

        for (String id : selectedIdList) {
            StringBuilder selectCourseUpdateInfoSql = new StringBuilder();
            selectCourseUpdateInfoSql.append("SELECT * FROM `" + kcgxfkTableName + "` T WHERE T.id = '" + id + "'");
            // 根据ID取得课程更新活动信息
            List<Map<String, Object>> resultCourseUpdateList = entityManager.createNativeQuery(selectCourseUpdateInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            String kcqdKcbh = (String) resultCourseUpdateList.get(0).get("kcbh");
            StringBuilder selectKcqdInfoSql = new StringBuilder();
            selectKcqdInfoSql.append("SELECT * FROM `" + kcqdTableName + "` T WHERE T.kcbh = '" + kcqdKcbh + "' ORDER BY createdTime DESC, modifiedTime DESC, sequenceNo DESC");
            // 根据kcbh取得课程更新活动信息
            List<Map<String, Object>> resultKcqdList = entityManager.createNativeQuery(selectKcqdInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            String kcqdId = (String) resultKcqdList.get(0).get("id");
            bizIdList.add(kcqdId);
            matchKcqdId.put(kcqdId, id);
            matchKcgxfkId.put(id, kcqdId);
        }

        if (CollectionUtils.isEmpty(bizIdList)) {
            return getErrResponseResult(-1L, "参数不能为空");
        }

        List<String> failList = new ArrayList<>();

        bizIdList.forEach(bizId -> {
            try {
                ResponseResult responseResult = courseBackUpToKcqdHistory(bizId);
                if (responseResult.getErrcode() != 0) {
                    failList.add(responseResult.getErrmsg());
                    String kcgxfkId = matchKcqdId.get(bizId);
                    Iterator<String> iterator = selectedIdList.iterator();
                    while (iterator.hasNext()) {
                        String next = iterator.next();
                        if (next.equals(kcgxfkId)) {
                            iterator.remove();
                        }
                    }
                }
            } catch (RuntimeException e) {

                failList.add(e.getMessage());
            } catch (Exception e) {
                failList.add(StrUtil.format("系统处理异常:{}", bizId));
            }
        });

        List<String> flushList = new ArrayList<>();
        flushList.addAll(selectedIdList);

        if (CollectionUtils.isEmpty(flushList)) {
            return getErrResponseResult(-1L, "参数不能为空");
        }

        flushList.forEach(bizId -> {
            try {
                ResponseResult responseResult = courseUpdateToKcqd(bizId, matchKcgxfkId);
                if (responseResult.getErrcode() != 0) {
                    failList.add(responseResult.getErrmsg());
                }
            } catch (RuntimeException e) {

                failList.add(e.getMessage());
            } catch (Exception e) {
                failList.add(StrUtil.format("系统处理异常:{}", bizId));
            }
        });

        if (CollectionUtils.isEmpty(failList)) {
            return getOkResponseResult("全部成功");
        } else if (bizIdList.size() == failList.size()) {
            return getErrResponseResult(-1L, StrUtil.format("更新全部失败:{}", JSON.toJSONString(failList)));
        } else {
            return getErrResponseResult(-1L, StrUtil.format("更新部分失败:{}", JSON.toJSONString(failList)));
        }
    }

    private ResponseResult courseBackUpToKcqdHistory(String bizId) {

        log.info("\n===========进入备份历史课程方法,bizId={}", bizId);
        ResponseResult.ResponseResultBuilder<Object> resp = ResponseResult.builder().errcode(-1l);

        //获取入库课程清单数据
        BizObjectCreatedModel kcqd = getBizObjectFacade().getBizObject("kcqd", bizId);

        if (kcqd == null) {
            return resp.errmsg("入库课程清单数据不存在").build();
        }

        String kcbh = kcqd.getString("kcbh");
        if (org.apache.commons.lang.StringUtils.isEmpty(kcbh)) {
            return resp.errmsg(StrUtil.format("课程编号不能为空:课程Id={}", bizId)).build();
        }

//        //判断课程更新数据是否存在
//        BizObjectQueryModel query = new BizObjectQueryModel();
//        query.setSchemaCode("kcgxfk");
//        query.setQueryCode("kcsb");
//        query.setPageable(new PageableImpl(0,10));
//        List<FilterExpression> itList = new ArrayList<>();
//        FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//        itList.add(it);
//        it = Q.it("gxfk", FilterExpression.Op.Eq, "更新");
//        itList.add(it);
//        it = Q.it("fbzt", FilterExpression.Op.NotEq, "已发布");
//        itList.add(it);
//        FilterExpression.And and = Q.and(itList);
//        query.setFilterExpr(and);
//        Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(query);
//
//        BizObjectQueryModel query2 = new BizObjectQueryModel();
//        query2.setSchemaCode("kcgxfk");
//        query2.setQueryCode("kcsb");
//        query2.setPageable(new PageableImpl(0,10));
//        List<FilterExpression> itList2 = new ArrayList<>();
//        FilterExpression.Item it2 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//        itList2.add(it2);
//        it2 = Q.it("gxfk", FilterExpression.Op.Eq, "未反馈");
//        itList2.add(it2);
//        FilterExpression.And and2 = Q.and(itList2);
//        query2.setFilterExpr(and2);
//        Page<BizObjectModel> page2 = bizObjectFacade.queryBizObjects(query2);
//
//        BizObjectQueryModel query3 = new BizObjectQueryModel();
//        query3.setSchemaCode("kcgxfk");
//        query3.setQueryCode("kcsb");
//        query3.setPageable(new PageableImpl(0,10));
//        List<FilterExpression> itList3 = new ArrayList<>();
//        FilterExpression.Item it3 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//        itList3.add(it3);
//        it3 = Q.it("gxfk", FilterExpression.Op.IsNull, null);
//        itList3.add(it3);
//        FilterExpression.And and3 = Q.and(itList3);
//        query3.setFilterExpr(and3);
//        Page<BizObjectModel> page3 = bizObjectFacade.queryBizObjects(query3);
//
//        if (page.getTotal() > 0 || page.getContent().size() > 0 || page2.getTotal() > 0 || page2.getContent().size() > 0 || page3.getTotal() > 0 || page3.getContent().size() > 0) {
//            return resp.errmsg(StrUtil.format("课程更新未反馈或已在更新中,课程编号:{}", kcbh)).build();
//        }

        //组合历史入库课程数据
        BizSchemaModel bizSchemaModel = this.getAppManagementFacade().getBizSchemaBySchemaCode("kcqdHistory", true);

        //获取数据项code , 不是子表,已发布,不是默认字段
        List<String> fieldList = bizSchemaModel.getProperties().stream()
                .filter(prop -> !prop.getDefaultProperty() && prop.getPropertyType() != BizPropertyType.CHILD_TABLE && prop.getPublished())
                .map(BizPropertyModel::getCode).collect(Collectors.toList());

        //创建备份普通数据
        Map<String, Object> data = new HashMap<>();
        fieldList.forEach(f -> data.put(f, kcqd.get(f)));

//        // 获取更新课程对应活动信息
//        CourseUpdateInfo courseUpdateInfo = gxhdInfo.get(bizId);


//        data.put("sbr",kcqd.get("creater"));
//        data.put("sbsj",kcqd.getCreatedTime());
//        data.put("kczt","未启用");
//        // 点赞数
//        data.put("dzs",kcqd.get("dzs"));
//        // 学习人次
//        data.put("xxrc",0);
//        // 当日是否学习
//        data.put("drsfxr",false);
//        // 是否已点赞
//        data.put("sfydz",false);
//        // 年度
//        data.put("psnd",kcqd.get("year"));
//        // 课程分类/
//        data.put("hdlb",kcqd.get("modality"));
//        // 开放范围
//        data.put("DropdownArea",kcqd.get("previewArea"));
//        // 可开放范围
//        data.put("StaffDeptMix",kcqd.get("kkffw"));
//        // 课程等级/评审级别
//        data.put("kcdj",kcqd.get("psjb"));
//        // 更新活动名称
//        data.put("gxhdmc", courseUpdateInfo.getGxhdmc());
//        // 更新活动截止时间
//        data.put("gxjzrq", courseUpdateInfo.getToTime());
        // 入库课程
        data.put("rkkc", bizId);
        // 附件拷贝
        attachmentService.attachmentCopy(data, Lists.newArrayList("kcfm", "jssc", "sjfj", "ckzl", "fj"));


//        // 课程中开发人，文本赋值
//        SelectionValue kczkfr = kcqd.getSelectionObject("kczkfr");
//        if (kczkfr != null) {
//            data.put("kczkfrtxt",kczkfr.getName());
//        }


        //创建子表数据,课程结构kcqdCourseStructures,判断题kcqdJudgmentQuestion,选择题kcqdChoiceQuestion

        List<String> subDefaultCodeList = new ArrayList<>(Arrays.asList("id", "parentId", "modifier", "modifiedTime"));
        //课程结构 kcqdCourseStructuresLs
        List<Map<String, Object>> courseStructuresList = (List<Map<String, Object>>) kcqd.getObject("kcqdCourseStructures");
        if (CollectionUtils.isNotEmpty(courseStructuresList)) {

            courseStructuresList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdCourseStructuresLs", courseStructuresList);
        }

        //课程结构 kcqdalkcjgLs
        List<Map<String, Object>> kcqdalkcjgList = (List<Map<String, Object>>) kcqd.getObject("kcqdalkcjg");
        if (CollectionUtils.isNotEmpty(kcqdalkcjgList)) {

            kcqdalkcjgList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdalkcjgLs", kcqdalkcjgList);
        }


//        判断题 kcqdJudgmentQuestionLs
        List<Map<String, Object>> judgmentQuestionList = (List<Map<String, Object>>) kcqd.getObject("kcqdJudgmentQuestion");
        if (CollectionUtils.isNotEmpty(judgmentQuestionList)) {

            judgmentQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdJudgmentQuestionLs", judgmentQuestionList);
        }

//        选择题 kcqdChoiceQuestionLs
        List<Map<String, Object>> choiceQuestionList = (List<Map<String, Object>>) kcqd.getObject("kcqdChoiceQuestion");
        if (CollectionUtils.isNotEmpty(choiceQuestionList)) {

            choiceQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdChoiceQuestionLs", choiceQuestionList);
        }

        BizObjectCreatedModel bizModel = new BizObjectCreatedModel("kcqdHistory", data, false);
        bizModel.setName(kcqd.getString("courseName"));
        bizModel.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String rkId = getBizObjectFacade().saveBizObject(getUserId(), bizModel, false);

        log.info("创建历史入库课程表单数据成功,返回id={}", rkId);


//        if (rkId != null) {
//            //修改课程申报状态 已入库, 申报进度
//
//            Map<String, Object> sbjd = new HashMap<>();
//            sbjd.put("sbjdt",4);
//            sbjd.put("ShortTextDQYW","已入库");
//            BizObjectCreatedModel sbjdBiz  = new BizObjectCreatedModel("kcsbNew", sbjd, false);
//            sbjdBiz.setId(bizId);
//            getBizObjectFacade().saveBizObject(getUserId(),sbjdBiz,false);
//        }


        return resp.errcode(0L).errmsg("历史入库课程保存成功").build();

    }

    private ResponseResult courseUpdateToKcqd(String bizId, Map<String, String> matchKcgxfkId) {

        log.info("\n===========进入更新入库课程清单方法,bizId={}", bizId);
        ResponseResult.ResponseResultBuilder<Object> resp = ResponseResult.builder().errcode(-1L);

        //获取课程更新反馈数据
        BizObjectCreatedModel kcgxfk = getBizObjectFacade().getBizObject("kcgxfk", bizId);

        if (kcgxfk == null) {
            return resp.errmsg("入库课程清单数据不存在").build();
        }

        String kcbh = kcgxfk.getString("kcbh");
        if (org.apache.commons.lang.StringUtils.isEmpty(kcbh)) {
            return resp.errmsg(StrUtil.format("课程编号不能为空:课程Id={}", bizId)).build();
        }

//        //判断课程更新数据是否存在
//        BizObjectQueryModel query = new BizObjectQueryModel();
//        query.setSchemaCode("kcgxfk");
//        query.setQueryCode("kcsb");
//        query.setPageable(new PageableImpl(0,10));
//        List<FilterExpression> itList = new ArrayList<>();
//        FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//        itList.add(it);
//        it = Q.it("gxfk", FilterExpression.Op.Eq, "更新");
//        itList.add(it);
//        it = Q.it("fbzt", FilterExpression.Op.NotEq, "已发布");
//        itList.add(it);
//        FilterExpression.And and = Q.and(itList);
//        query.setFilterExpr(and);
//        Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(query);
//
//        BizObjectQueryModel query2 = new BizObjectQueryModel();
//        query2.setSchemaCode("kcgxfk");
//        query2.setQueryCode("kcsb");
//        query2.setPageable(new PageableImpl(0,10));
//        List<FilterExpression> itList2 = new ArrayList<>();
//        FilterExpression.Item it2 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//        itList2.add(it2);
//        it2 = Q.it("gxfk", FilterExpression.Op.Eq, "未反馈");
//        itList2.add(it2);
//        FilterExpression.And and2 = Q.and(itList2);
//        query2.setFilterExpr(and2);
//        Page<BizObjectModel> page2 = bizObjectFacade.queryBizObjects(query2);
//
//        BizObjectQueryModel query3 = new BizObjectQueryModel();
//        query3.setSchemaCode("kcgxfk");
//        query3.setQueryCode("kcsb");
//        query3.setPageable(new PageableImpl(0,10));
//        List<FilterExpression> itList3 = new ArrayList<>();
//        FilterExpression.Item it3 = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//        itList3.add(it3);
//        it3 = Q.it("gxfk", FilterExpression.Op.IsNull, null);
//        itList3.add(it3);
//        FilterExpression.And and3 = Q.and(itList3);
//        query3.setFilterExpr(and3);
//        Page<BizObjectModel> page3 = bizObjectFacade.queryBizObjects(query3);
//
//        if (page.getTotal() > 0 || page.getContent().size() > 0 || page2.getTotal() > 0 || page2.getContent().size() > 0 || page3.getTotal() > 0 || page3.getContent().size() > 0) {
//            return resp.errmsg(StrUtil.format("课程更新未反馈或已在更新中,课程编号:{}", kcbh)).build();
//        }

        //组合入库课程清单数据
        BizSchemaModel bizSchemaModel = this.getAppManagementFacade().getBizSchemaBySchemaCode("kcqd", true);

        //获取数据项code , 不是子表,已发布,不是默认字段
        List<String> fieldList = bizSchemaModel.getProperties().stream()
                .filter(prop -> !prop.getDefaultProperty() && prop.getPropertyType() != BizPropertyType.CHILD_TABLE && prop.getPublished())
                .map(BizPropertyModel::getCode).collect(Collectors.toList());

        //创建更新普通数据
        Map<String, Object> data = new HashMap<>();
        fieldList.forEach(f -> data.put(f, kcgxfk.get(f)));

//        // 获取更新课程对应活动信息
//        CourseUpdateInfo courseUpdateInfo = gxhdInfo.get(bizId);


//        data.put("sbr",kcqd.get("creater"));
//        data.put("sbsj",kcqd.getCreatedTime());
//        data.put("kczt","未启用");
//        // 点赞数
//        data.put("dzs",kcqd.get("dzs"));
//        // 学习人次
//        data.put("xxrc",0);
//        // 当日是否学习
//        data.put("drsfxr",false);
//        // 是否已点赞
//        data.put("sfydz",false);
//        // 年度
//        data.put("psnd",kcqd.get("year"));
//        // 课程分类/
//        data.put("hdlb",kcqd.get("modality"));
        // 开放范围
        data.put("previewArea", kcgxfk.get("DropdownArea"));
//        // 可开放范围
//        data.put("StaffDeptMix",kcqd.get("kkffw"));
        // 课程等级/评审级别
        data.put("psjb", kcgxfk.get("kcdj"));
//        // 更新活动名称
//        data.put("gxhdmc", courseUpdateInfo.getGxhdmc());
//        // 更新活动截止时间
//        data.put("gxjzrq", courseUpdateInfo.getToTime());
        // 存入更新id
        data.put("id", MapUtils.getString(matchKcgxfkId, bizId, null));
        // 附件拷贝
        attachmentService.attachmentCopy(data, Lists.newArrayList("kcfm", "jssc", "sjfj", "ckzl", "fj"));


//        // 课程中开发人，文本赋值
//        SelectionValue kczkfr = kcqd.getSelectionObject("kczkfr");
//        if (kczkfr != null) {
//            data.put("kczkfrtxt",kczkfr.getName());
//        }


        //创建子表数据,课程结构kcqdCourseStructures,判断题kcqdJudgmentQuestion,选择题kcqdChoiceQuestion

        List<String> subDefaultCodeList = new ArrayList<>(Arrays.asList("id", "parentId", "modifier", "modifiedTime"));
        //课程结构 kcqdCourseStructures
        List<Map<String, Object>> courseStructuresList = (List<Map<String, Object>>) kcgxfk.getObject("courseStructureskcgxfk");
        if (CollectionUtils.isNotEmpty(courseStructuresList)) {

            courseStructuresList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdCourseStructures", courseStructuresList);
        }

        //课程结构 kcqdalkcjg
        List<Map<String, Object>> kcqdalkcjgList = (List<Map<String, Object>>) kcgxfk.getObject("kcqdalkcjgkcgxfk");
        if (CollectionUtils.isNotEmpty(kcqdalkcjgList)) {

            kcqdalkcjgList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdalkcjg", kcqdalkcjgList);
        }


//        判断题 kcqdJudgmentQuestion
        List<Map<String, Object>> judgmentQuestionList = (List<Map<String, Object>>) kcgxfk.getObject("judgmentQuestionkcgxfk");
        if (CollectionUtils.isNotEmpty(judgmentQuestionList)) {

            judgmentQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdJudgmentQuestion", judgmentQuestionList);
        }

//        选择题 kcqdChoiceQuestion
        List<Map<String, Object>> choiceQuestionList = (List<Map<String, Object>>) kcgxfk.getObject("choiceQuestionkcgxfk");
        if (CollectionUtils.isNotEmpty(choiceQuestionList)) {

            choiceQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdChoiceQuestion", choiceQuestionList);
        }

        BizObjectCreatedModel bizModel = new BizObjectCreatedModel("kcqd", data, false);
        bizModel.setName(kcgxfk.getString("courseName"));
        bizModel.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String rkId = getBizObjectFacade().saveBizObject(getUserId(), bizModel, false);

        log.info("创建入库课程清单新数据表单数据成功,返回id={}", rkId);


//        if (rkId != null) {
//            //修改课程申报状态 已入库, 申报进度
//
//            Map<String, Object> sbjd = new HashMap<>();
//            sbjd.put("sbjdt",4);
//            sbjd.put("ShortTextDQYW","已入库");
//            BizObjectCreatedModel sbjdBiz  = new BizObjectCreatedModel("kcsbNew", sbjd, false);
//            sbjdBiz.setId(bizId);
//            getBizObjectFacade().saveBizObject(getUserId(),sbjdBiz,false);
//        }

        if (rkId != null) {
//            // 获取课程更新活动表名
//            String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
//            StringBuilder selectKcqdInfoSql = new StringBuilder();
//            selectKcqdInfoSql.append("SELECT * FROM " + kcqdTableName + " WHERE kcbh = '" + kcbh + "' ORDER BY createdTime DESC, modifiedTime DESC, sequenceNo DESC;");
//            // 根据ID取得课程更新活动信息
//            List<Map<String, Object>> kcqdList = entityManager.createNativeQuery(selectKcqdInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            // 删除课程清单中当前相同课程编号的旧课程
//            if (CollectionUtils.isNotEmpty(kcqdList) && kcqdList.size() > 1) {
//                kcqdList.remove(0);
//                List<String> ids = new ArrayList<>();
//                for (Map<String, Object> stringObjectMap : kcqdList) {
//                    String id = (String) stringObjectMap.get("id");
//                    ids.add(id);
//                }
//                if (CollectionUtils.isNotEmpty(ids)) {
//                    Boolean deleted = bizObjectFacade.removeBizObjects(getUserId(), "kcqd", ids);
//                    if (deleted) {
//                        log.info("删除入库课程清单表单旧课程数据成功,返回id={}", ids);
//                    }
//                }
//            }

            //修改课程申报状态 已入库, 申报进度
            Map<String, Object> gxzt = new HashMap<>();
            gxzt.put("gxzt", "已发布");
            BizObjectCreatedModel sbjdBiz = new BizObjectCreatedModel("kcgxfk", gxzt, false);
            sbjdBiz.setId(bizId);
            getBizObjectFacade().saveBizObject(getUserId(), sbjdBiz, false);
        }


        return resp.errcode(0L).errmsg("课程更新反馈成功").build();

    }

//    private void courseTransfer(String userId, List<Map<String, Object>> resultList, List<Map<String, Object>> maps, boolean isActive,
//                                String kcqdCourseStructuresTabName, String kcqdJudgmentQuestionTabName, String kcqdChoiceQuestionTabName, String sheet_kcqd_psdfTabName,
//                                String courseStructures, String judgmentQuestion, String choiceQuestion, String psdfb,
//                                String target) {
//        for (Map<String, Object> map : maps) {
//            Map<String, Object> kcgxfkMap = new HashMap<>();
//            kcgxfkMap.put("sequenceStatus", map.get("sequenceStatus"));
//            kcgxfkMap.put("LongText1639381871412", map.get("LongText1639381871412"));
//            kcgxfkMap.put("LongText1639381934038", map.get("LongText1639381934038"));
//            kcgxfkMap.put("num", map.get("num"));
//            kcgxfkMap.put("xxrc", map.get("xxrc"));
//            kcgxfkMap.put("kcbh", map.get("kcbh"));
//            kcgxfkMap.put("xmb", map.get("xmb"));
//            kcgxfkMap.put("courseName", map.get("courseName"));
//            kcgxfkMap.put("kkffw", map.get("kkffw"));
//            kcgxfkMap.put("year", map.get("year"));
//            kcgxfkMap.put("ownerDeptQueryCode", map.get("ownerDeptQueryCode"));
//            kcgxfkMap.put("sfydz", map.get("sfydz"));
//            kcgxfkMap.put("classHour", map.get("classHour"));
//            kcgxfkMap.put("sbr", map.get("sbr"));
//            kcgxfkMap.put("dzs", map.get("dzs"));
//            kcgxfkMap.put("workflowInstanceId", map.get("workflowInstanceId"));
//            kcgxfkMap.put("name", map.get("name"));
//            kcgxfkMap.put("kczkfrgh", map.get("kczkfrgh"));
//            kcgxfkMap.put("version", map.get("version"));
//            kcgxfkMap.put("cultivateObj", map.get("cultivateObj"));
//            kcgxfkMap.put("djl", map.get("djl"));
//            kcgxfkMap.put("owner", map.get("owner"));
//            kcgxfkMap.put("createdDeptId", map.get("createdDeptId"));
//            kcgxfkMap.put("xzl", map.get("xzl"));
//            kcgxfkMap.put("cultivateWay", map.get("cultivateWay"));
//            kcgxfkMap.put("kczt", map.get("kczt"));
//            kcgxfkMap.put("createdTime", map.get("createdTime"));
//            kcgxfkMap.put("modifiedTime", map.get("modifiedTime"));
//            kcgxfkMap.put("drsfxr", map.get("drsfxr"));
//            kcgxfkMap.put("sqkcrc", map.get("sqkcrc"));
//            kcgxfkMap.put("modality", map.get("modality"));
//            kcgxfkMap.put("psnd", map.get("psnd"));
//            kcgxfkMap.put("kczkfr", map.get("kczkfr"));
//            kcgxfkMap.put("psjb", map.get("psjb"));
//            kcgxfkMap.put("tdcy", map.get("tdcy"));
//            kcgxfkMap.put("kcsbtz", map.get("kcsbtz"));
//            kcgxfkMap.put("sbsj", map.get("sbsj"));
//            kcgxfkMap.put("creater", map.get("creater"));
//            kcgxfkMap.put("sequenceNo", map.get("sequenceNo"));
//            kcgxfkMap.put("szdw", map.get("szdw"));
//            kcgxfkMap.put("category", map.get("category"));
//            kcgxfkMap.put("ownerDeptId", map.get("ownerDeptId"));
//            kcgxfkMap.put("modifier", map.get("modifier"));
//            kcgxfkMap.put("LongText1639381938724", map.get("LongText1639381938724"));
//            kcgxfkMap.put("kczkfrtxt", map.get("kczkfrtxt"));
//            kcgxfkMap.put("series", map.get("series"));
//            kcgxfkMap.put("LongText1639381733243", map.get("LongText1639381733243"));
//            kcgxfkMap.put("previewArea", map.get("previewArea"));
//            kcgxfkMap.put("kcxl", map.get("kcxl"));
//            kcgxfkMap.put("zxgxsj", map.get("modifiedTime"));
//            kcgxfkMap.put("modality", map.get("modality"));
//            kcgxfkMap.put("jxnd", map.get("jxnd"));
//            kcgxfkMap.put("kcjj", map.get("kcjj"));
//            kcgxfkMap.put("gxmb", map.get("gxmb"));
//            kcgxfkMap.put("lxmb", map.get("lxmb"));
//            kcgxfkMap.put("alms", map.get("alms"));
//            kcgxfkMap.put("ldjy", map.get("ldjy"));
//            kcgxfkMap.put("sc", map.get("sc"));
//            if (isActive) {
//                kcgxfkMap.put("gxhdmc", resultList.get(0).get("gxhdmc"));
//                kcgxfkMap.put("gxjzrq", resultList.get(0).get("toTime"));
//            }
//            String sheetId = (String) map.get("id");
//            List<Map<String, Object>> sheetInfoA = getSheetInfo(kcqdCourseStructuresTabName, sheetId);
//            List<Map<String, Object>> sheetInfoB = getSheetInfo(kcqdJudgmentQuestionTabName, sheetId);
//            List<Map<String, Object>> sheetInfoC = getSheetInfo(kcqdChoiceQuestionTabName, sheetId);
//            List<Map<String, Object>> sheetInfoD = getSheetInfo(sheet_kcqd_psdfTabName, sheetId);
//            // 子表
//            kcgxfkMap.put(courseStructures, sheetInfoA);
//            kcgxfkMap.put(judgmentQuestion, sheetInfoB);
//            kcgxfkMap.put(choiceQuestion, sheetInfoC);
//            kcgxfkMap.put(psdfb, sheetInfoD);
//            List<Map<String, Object>> sjfjAttachList = getAttachInfo(sheetId, "sjfj");
//            List<Map<String, Object>> jsscAttachList = getAttachInfo(sheetId, "jssc");
//            List<Map<String, Object>> ckzlAttachList = getAttachInfo(sheetId, "ckzl");
//            // 附件
//            kcgxfkMap.put("sjfj", sjfjAttachList);
//            kcgxfkMap.put("jssc", jsscAttachList);
//            kcgxfkMap.put("ckzl", ckzlAttachList);
////                BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcqd", (String) map.get("id"));
//            BizObjectCreatedModel kcgxfk = new BizObjectCreatedModel(target, kcgxfkMap, false);
//            kcgxfk.setSequenceStatus(SequenceStatus.COMPLETED.name());
//            String checkInfoId = getBizObjectFacade().saveBizObject(userId, kcgxfk, false);
//            log.info("\n=======课程更新反馈表单保存成功,bizObjectId={}", checkInfoId);
//        }
//    }

//    /**
//     * 更新课程数据并备份至历史课程信息
//     *
//     * @param ids
//     * @return
//     */
//    @GetMapping("courseUpdateToSystem")
//    @Transactional
//    public ResponseResult courseUpdateToSystem(@RequestParam String ids) {
//
//        String userId = getUserId();
//
//        String[] splitID = ids.split(";");
//
//        List<String> kcbhList = new ArrayList<>();
//        for (int j = 0; j < splitID.length; j++) {
//            BizObjectCreatedModel kcqdHistory = getBizObjectFacade().getBizObject("kcgxfk", splitID[j]);
//            Map<String, Object> data = kcqdHistory.getData();
//            String kcbh = (String) data.get("kcbh");
//            kcbhList.add(kcbh);
//        }
//        String tableName = getBizObjectFacade().getTableName("kcqd");
//        List<Map<String, Object>> maps = courseUpdateRepository.kcqdUpdateList(kcbhList);
//        // 获取源数据子表表名
//        String kcqdCourseStructuresTabName = getBizObjectFacade().getTableName("kcqdCourseStructures");
//        String kcqdJudgmentQuestionTabName = getBizObjectFacade().getTableName("kcqdJudgmentQuestion");
//        String kcqdChoiceQuestionTabName = getBizObjectFacade().getTableName("kcqdChoiceQuestion");
//        String Sheet_kcqd_psdfTabName = getBizObjectFacade().getTableName("Sheet_kcqd_psdf");
//
//        courseTransfer(userId, null, maps, false, kcqdCourseStructuresTabName, kcqdJudgmentQuestionTabName, kcqdChoiceQuestionTabName, Sheet_kcqd_psdfTabName,
//                "kcqdCourseStructuresLs", "kcqdJudgmentQuestionLs", "kcqdChoiceQuestionLs", "Sheet_kcqdHistory_psdf",
//                "kcqdHistory");
//
//        for (int j = 0; j < splitID.length; j++) {
//
//            BizObjectCreatedModel kcqdHistory = getBizObjectFacade().getBizObject("kcgxfk", splitID[j]);
//            Map<String, Object> data = kcqdHistory.getData();
//            String kcbh = (String) data.get("kcbh");
//
//            BizObjectQueryModel queryModel = new BizObjectQueryModel();
//            queryModel.setSchemaCode("kcqd");
//            queryModel.setQueryCode("kcqd");
//            queryModel.setPageable(new PageableImpl(0, 20));
//
//            FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);
//
//            queryModel.setFilterExpr(it);
//
//            Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
//
//            BizObjectModel courseInfoModel;
//            if (page.getTotal() == 0) {
//                log.info("\n=======================课程编号：" + kcbh + "在入库课程清单中不存在");
//                return getErrResponseResult(500L, "课程编号：" + kcbh + "在入库课程清单中不存在");
//            } else {
//                courseInfoModel = page.getContent().get(0);
//            }
////            String courseName = MapUtils.getString(courseInfoModel.getData(), "courseName");
////            Map<String, Object> data1 = courseInfoModel.getData();
////            courseInfoModel.put("courseName", courseName + 24);
////            courseInfoModel.put("cultivateWay", "培训方式");
////            String bizObject = getBizObjectFacade().saveBizObject(userId, courseInfoModel, false);
//            getBizObjectFacade().deleteBizObject("kcqd", MapUtils.getString(courseInfoModel.getData(), "id"));
//        }
//
//        String kcgxfkTableName = getBizObjectFacade().getTableName("kcgxfk");
//        List<Map<String, Object>> kcgxfkMaps = courseUpdateRepository.kcgxfkUpdateList(kcbhList);
//        // 获取源数据子表表名
//        String courseStructuresTabName = getBizObjectFacade().getTableName("courseStructureskcgxfk");
//        String judgmentQuestionTabName = getBizObjectFacade().getTableName("judgmentQuestionkcgxfk");
//        String choiceQuestionTabName = getBizObjectFacade().getTableName("choiceQuestionkcgxfk");
//        String psdfbTabName = getBizObjectFacade().getTableName("psdfbkcgxfk");
//        courseTransfer(userId, null, kcgxfkMaps, false, courseStructuresTabName, judgmentQuestionTabName, choiceQuestionTabName, psdfbTabName,
//                "kcqdCourseStructures", "kcqdJudgmentQuestion", "kcqdChoiceQuestion", "Sheet_kcqd_psdf",
//                "kcqd");
//
//        return getOkResponseResult("success");
//    }

//    /**
//     * 子表信息查询
//     *
//     * @param kcqdCourseStructuresTabName
//     * @param sheetId
//     * @return
//     */
//    private List<Map<String, Object>> getSheetInfo(String kcqdCourseStructuresTabName, String sheetId) {
//        StringBuilder selectSheetSql = new StringBuilder();
//        selectSheetSql.append("SELECT * FROM `" + kcqdCourseStructuresTabName + "` T WHERE T.parentId = '" + sheetId + "'");
//        // 根据ID取得课程更新活动子表，待更新课程信息
//        List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectSheetSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//        for (Map<String, Object> stringObjectMap : resultList) {
//            stringObjectMap.put("id", "");
//            stringObjectMap.put("parentId", "");
//            stringObjectMap.put("rowStatus", "Added");
//        }
//        return resultList;
//    }

    //    /**
//     * 附件查询信息
//     *
//     * @param bizObjId
//     * @param bizPropertyCode
//     * @return
//     */
//    private List<Map<String, Object>> getAttachInfo(String bizObjId, String bizPropertyCode) {
//        StringBuilder selectSheetSql = new StringBuilder();
//        selectSheetSql.append("SELECT * FROM `h_biz_attachment` T WHERE T.bizObjectId = '" + bizObjId + "' AND T.bizPropertyCode = '" + bizPropertyCode + "';");
//        // 根据ID取得课程更新活动子表，待更新课程信息
//        List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectSheetSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//        return resultList;
//    }
    @PostMapping("cancelActivity")
    @Transactional
    public ResponseResult cancelActivity(@RequestBody List<String> bizId) {

        // 获取课程更新活动子表通知更新课程清单表名
        String kcgxfkTableName = getBizObjectFacade().getTableName("kcgxfk");

        for (String id : bizId) {
            StringBuilder cancelCourseUpdateSql = new StringBuilder();
            cancelCourseUpdateSql.append("UPDATE " + kcgxfkTableName + " SET cancel = '取消' WHERE activeId = '" + id + "';");
            int result = entityManager.createNativeQuery(cancelCourseUpdateSql.toString()).executeUpdate();
        }

        return getOkResponseResult("取消启动成功");
    }

    /**
     * 点击量,下载量修改,加入我的学习
     *
     * @param bizId
     * @param type
     */
    @GetMapping("courseStatisticsNew")
    public ResponseResult courseStatisticsNew(@RequestParam String bizId, @RequestParam Integer type, @RequestParam String userId) {
        log.info("\n==========进入点击量增加方法:bizId={},type={},userId={}", bizId, type, userId);
        ResponseResult.ResponseResultBuilder<Object> resp = ResponseResult.builder().errcode(-1L);
        if (org.apache.commons.lang.StringUtils.isEmpty(bizId) || type == null || (type != 1 && type != 2) || org.apache.commons.lang.StringUtils.isEmpty(userId)) {
            return resp.errmsg(StrUtil.format("参数不能为空:课程Id={}，增加类型={}，userId={}", bizId, type, userId)).build();
        } else {
            if (type == 1) {
                pocZcController.incrCourseStatisticsNew(bizId, type);
            } else if (type == 2) {
                pocZcController.incrCourseStatisticsNew(bizId, type);
                pocZcController.joinMyStudy(bizId, userId);
            } else {
                return resp.errmsg(StrUtil.format("type不符合预设条件，1 点击量, 2.下载(预览,学习)量，type={}", type)).build();
            }
            return resp.errcode(0L).errmsg("操作成功").build();
        }
    }

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 判断模型编码是否属于"zsgl"应用之下
     *
     * @param schemaCode
     * @return
     */
    @GetMapping("getTitle")
    public ResponseResult<Boolean> getTitle(@RequestParam String schemaCode) {
        log.info("\n>>>>>>获取模型所在应用code方法:schemaCode={}<<<<<<", schemaCode);

        String redisKey = "schemaCodeForTitle";
        boolean data = false;

        Boolean aBoolean = redisTemplate.hasKey(redisKey);
        BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(redisKey);
        if (!aBoolean) {
            StringBuilder getSchemaCodeListSql = new StringBuilder();
            getSchemaCodeListSql.append("SELECT `code` FROM `h_app_function` WHERE appCode = 'zsgl' AND type = 'BizModel';");
            List<String> getSchemaCodeList = entityManager.createNativeQuery(getSchemaCodeListSql.toString()).unwrap(NativeQueryImpl.class).getResultList();
            String[] array = getSchemaCodeList.toArray(new String[]{});
            boundSetOperations.add(array);
            boundSetOperations.expire(3600, TimeUnit.SECONDS);
        }
        data = boundSetOperations.isMember(schemaCode);
        return getOkResponseResult(data, "success");
    }
}
